如何获取文字尺寸?

时间:2015-08-02 07:54:28

标签: javascript html getboundingclientrect

此片段给出" 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或更改元素的样式。

4 个答案:

答案 0 :(得分:0)

如果您无法更改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);

答案 1 :(得分:0)

根据我所知,或者可以告诉我们,在不使用额外(内联,通常是不可见)元素的情况下,单独获取元素的文本宽度是不可能的。 /> 对于那些没有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);

答案 2 :(得分:0)

您可以使用Range来衡量文字。例如:

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

答案 3 :(得分:0)

您可以使用clientWidth或offsetWidth

Use var offsetWidth =element.offsetWidth; 

差异是offsetWidth包含边框宽度,clientWidth不是

enter image description here

相关问题