2

这段代码给出了“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

4 回答 4

0

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

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>

于 2015-08-02T08:36:40.210 回答
0

您可以使用 clientWidth 或 offsetWidth

Use var offsetWidth =element.offsetWidth; 

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

在此处输入图像描述

于 2015-08-02T09:22:10.560 回答
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);
于 2015-08-02T08:19:26.353 回答
0

如果您不能更改 dom,那么您可以theDiv inline-block通过 CSS 进行:

#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);
于 2015-08-02T08:04:06.583 回答