简体   繁体   English

如何找到网页上隐藏文字的宽度?

[英]How to find the width of hidden text on the webpage?

So I am trying to add this tooltip, which gets resized based on the width of the text it contains. 因此,我尝试添加此工具提示,该提示将根据其包含的文本的宽度进行调整。 Tooltip is a div and it has another div containing the text. 工具提示是一个div,它还有另一个包含文本的div。

<div><div> tooltip text </div></div>

I assign text to it using javascript as mytooltiptext.innerHTML=sometext. 我使用javascript作为mytooltiptext.innerHTML = sometext将文本分配给它。 The tooltip is hidden with display set to none, and becomes visible on mouse hover. 该工具提示被隐藏,显示设置为“无”,并且在鼠标悬停时可见。 I am trying to set its width before it even becomes visible based on the width of the text/text containing div. 我正在尝试根据包含div的文本/文本的宽度设置它的宽度,使其甚至变得不可见。 But when I try to get the clientWidth or scrollWidth of the text containing div, it comes out as zero. 但是,当我尝试获取包含div的文本的clientWidth或scrollWidth时,结果为零。 My understanding is that it is happening due to the element being hidden. 我的理解是,由于元素被隐藏,它正在发生。 I tried setting its display to block and visibility to hidden and then tried to get the requisite values, but to no avail. 我尝试将其显示设置为“阻止”,将可见性设置为“隐藏”,然后尝试获取必要的值,但无济于事。 Is there a way to get the width of hidden text without making it visible first? 有没有一种方法可以隐藏文本的宽度而不先使其可见?

Don't hide it, move it off screen then bring it back on hover. 不要隐藏它,将其移离屏幕,然后将其重新悬停。

CSS: CSS:

.inputtext span {
margin-left: -999em;
position: absolute;
}

.inputtext:hover span {
position: absolute;
left: 1em;
top: 2em;
z-index: 99;
margin-left: 0;
}​

HTML: HTML:

<div class="inputtext">Hover Me<span id="hiddenText">
This is the hidden text and some more text</span></div>​

Demo: http://jsfiddle.net/calder12/PBsJA/3/ 演示: http : //jsfiddle.net/calder12/PBsJA/3/

You could draw it way offscreen. 您可以将其绘制到屏幕外。 something like: 就像是:

.myCssStyle{
  position: absolute;
  right: 5000px;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM