How can you measure the space that a text will take in Javascript?

前端 未结 3 440
轻奢々
轻奢々 2020-12-30 15:13

In Javascript, I have a certain string, and I would like to somehow measure how much space (in pixels) it will take within a certain element.

Basically what I have i

相关标签:
3条回答
  • 2020-12-30 15:31

    try this

    http://blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/

    0 讨论(0)
  • 2020-12-30 15:33

    Given this HTML <span>text here</span> you have to read the offsetWidth attribute of the span, which is only assigned when the element itself is added to the DOM without a style that makes it invisible. Technically what this means is that the browser has to be able to visually load the element in the DOM to be able to construct and assign the offsetWidth attribute.

    Something like this would work:

    var span = document.createElement("span");
    span.appendChild(document.createTextNode("text here"));
    
    span.style = ""; // to make sure the elment doesn't have "display: none" or such
    document.body.appendChild(span); // adding it to the DOM
    
    var textWidth = span.offsetWidth;
    
    // be sure to hide or remove the span if you don't need it anymore
    
    0 讨论(0)
  • 2020-12-30 15:41

    This is easy using a JavaScript framework. I'm using Prototype in this example.

    <span id='text' style='border:1px solid #000000;font-size:14px'>hello this is sample text</span>
    
    <script type="text/javascript">
    alert($('text').getWidth())
    </script>
    
    0 讨论(0)
提交回复
热议问题