Knowing how wide the text string in HTML will be for word wrapping and other applications

Do you know a good cross-browser way to find out how wide the text string will be so that you can split it exactly so that it matches a fixed width?

Suppose you want to break long text, for example, so that it does not overflow the container with a fixed width, but you want the line to break the proximity to the border, so guess where to insert & shy; s is not a clean solution.

I want to research, I suppose it can be done with an invisible div, and then print a line inside it and check the width of the div or something like that with Javascript.

Has anyone done something like this?

* (focus is not word wrap, it's just an application that comes to my mind right now, but knowing the width of the text is what I want)

+5
source share
1 answer

Here is the full Hit Robinson (is this link appropriate?).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script type="text/javascript">
        function txtContent_onchange()
        {
            var span = document.getElementById("spanMeasure")
            span.innerHTML = "";
            span.appendChild(document.createTextNode(this.value));
            document.getElementById("txtWidth").value = span.scrollWidth;

        }
    </script>
    <style type="text/css">
        #spanMeasure 
        {
            position:absolute;
            top:0px;
            left:0px;
            visibility:hidden;
            width:10px;
            white-space:nowrap;
            overflow:hidden
        }
    </style>
</head>
<body>

    <input id="txtContent" onchange="txtContent_onchange.call(this)" /><br />
    <input id="txtWidth" />
    <span id="spanMeasure"><span>

</body>
</html>

The configuration of the span element is important here. This item will not affect the appearance of the page. The scrollWidth property will return the length of the text contained in it. Of course, you will need to set any font style attributes to get a reasonable value.

According to quirksmode , the Opera site may be a little flaky with this approach, but I suspect it is the closest cross-browser solution to you.

+2
source

All Articles