【问题标题】:How can I get text dimensions?如何获得文本尺寸?
【发布时间】:2015-08-02 07:54:28
【问题描述】:

这个sn-p给出了“theDiv”的宽度,等于页面的宽度:

<div id="theDiv">This is some text</div>
<script>
    var rect = document.getElementById("theDiv").getBoundingClientRect();
    alert("width of text is (not): " + rect.width);
</script>

有什么方法可以获取 div 中实际文本的宽度(和高度)?

注意:我正在开发一个分析网页的 chrome 扩展 - 我无法更改 dom 和 css,这意味着我不能使用 span 代替 div 或更改元素的样式。

【问题讨论】:

  • 你能用画布吗?
  • 如果元素是隐藏的,即完全不影响任何形状或形式的可见页面,您能否向 DOM 添加元素?
  • 我根本无法修改dom。

标签: javascript html getboundingclientrect


【解决方案1】:

您可以使用Range 来测量文本。例如:

var range = document.createRange();
range.selectNodeContents(document.getElementById("theDiv"));
var rect = range.getBoundingClientRect();
document.getElementById("out").innerHTML = "width of text is: " + rect.width;
<div id="theDiv">This is some text</div>
<div id="out"></div>

【讨论】:

    【解决方案2】:

    如果您无法更改 dom,那么您可以通过 CSS 制作 theDiv inline-block

    #theDiv {
       display: inline-block
    } 
    

    好的,在这种情况下,您可以创建虚拟元素,将其附加到 dom,计算尺寸,然后将其从 dom 中删除:

    // fetch source element and his content
    var div = document.getElementById("theDiv"),
        text = div.innerHTML;
    
    // create virtual span to calculate dimestions
    var span = document.body.appendChild(document.createElement('span'));
        span.innerHTML = text,
        rect = span.getBoundingClientRect();
    
    alert(rect.width);
    
    // remove virtual span from the DOM
    document.body.removeChild(span);
    

    【讨论】:

    • 对不起,我扩展了我的注释:我也无法更改 css 文件。
    【解决方案3】:

    据我所知,如果不使用额外的(内联,通常是不可见的)元素,单独获取元素文本的宽度是不可能的。
    但是对于那些没有OP限制到达这里的其他人,可以只使用JS并且完全不影响页面的流程。

    var target = ... // Whichever element's text's width you wish to measure
    var ruler = document.createElement("span");
    
    ruler.style.position = "absolute"; // remove from the page's flow
    ruler.style.visibility = "hidden"; // and totally stop it from being rendered
    
    // copy font-size, font-family and the text itself
    ruler.style.fontSize = target.style.fontSize;
    ruler.style.fontFamily = target.style.fontFamily;
    ruler.innerHTML = target.innerHTML;
    
    // add to the document so that the styles get applied, allowing us to discover its width
    document.body.appendChild(ruler);
    var textWidth = ruler.offsetWidth;
    // and then promptly remove again from the document
    document.body.removeChild(ruler);
    

    【讨论】:

      【解决方案4】:

      你可以使用clientWidth或offsetWidth

      Use var offsetWidth =element.offsetWidth; 
      

      不同的是offsetWidth包含边框宽度,clientWidth不包含

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-23
        • 1970-01-01
        • 1970-01-01
        • 2010-11-18
        • 2011-04-14
        相关资源
        最近更新 更多