Javascript 使用 jQuery 获取元素的实际宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10277323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get real width of elements with jQuery
提问by Alp
I am writing a validator for "visual correctness" of html files. The goal is to detect too wide elements.
我正在为 html 文件的“视觉正确性”编写验证器。目标是检测太宽的元素。
The dotted red line is an indicator of the max width of the document (200px in this example). The first paragraph is fine, but the second is too wide. Nevertheless, all of the following commands still return "200px" as the width:
红色虚线表示文档的最大宽度(在本例中为 200px)。第一段很好,但第二段太宽了。尽管如此,以下所有命令仍然返回“200px”作为宽度:
// all return 200, but the value should be larger
$('#two').width();
$('#two').outerWidth();
$('#two').prop('clientWidth');
Please see the Fiddlefor more details.
有关更多详细信息,请参阅Fiddle。
How can i detect such oversized elements?
我怎样才能检测到这样的超大元素?
Updated question:Better to ask, how can i detect text that exceeds the borders of their parent elements?
更新的问题:最好问一下,我如何检测超出其父元素边界的文本?
Updated requirement:I am not allowed to change anything in the source HTML or CSS. But i can do anything i want with jQuery to modify the document, so that i can detect those too wide elements.
更新要求:我不允许更改源 HTML 或 CSS 中的任何内容。但是我可以用 jQuery 做任何我想做的事情来修改文档,这样我就可以检测那些太宽的元素。
采纳答案by Dagg Nabbit
As others have said, temporarily wrap the text node in an inline element.
正如其他人所说,暂时将文本节点包装在内联元素中。
var two = document.getElementById('two'),
text = two.firstChild,
wrapper = document.createElement('span');
// wrap it up
wrapper.appendChild(text);
two.appendChild(wrapper);
// better than bad, it's good.
console.log(wrapper.offsetWidth);
// put it back the way it was.
two.removeChild(wrapper);
two.appendChild(text);
Here is a getInnerWidthfunction that should be useful to you. Pass it an element and it will handle the wrapping and unwrapping.
这是一个getInnerWidth应该对您有用的功能。向它传递一个元素,它将处理包装和展开。
function getInnerWidth(element) {
var wrapper = document.createElement('span'),
result;
while (element.firstChild) {
wrapper.appendChild(element.firstChild);
}
element.appendChild(wrapper);
result = wrapper.offsetWidth;
element.removeChild(wrapper);
while (wrapper.firstChild) {
element.appendChild(wrapper.firstChild);
}
return result;
}
回答by NateQ
scrollWidth will do it:
scrollWidth 会这样做:
$("#two").get()[0].scrollWidth or getElementById("two").scrollWidth
$("#two").get()[0].scrollWidth 或 getElementById("two").scrollWidth
this outputs 212px, the real width you are looking for.
这输出 212px,你正在寻找的实际宽度。
回答by Alon Gubkin
This effect is called "shrinkwrapping", and there's a couple of ways to determine the "real" width of the element.
这种效果称为“收缩包裹”,有几种方法可以确定元素的“真实”宽度。
Float
漂浮
One of the ways that you can use is to float your <p>element which will force it as small as possible, but you'll need to use a clearfixif anything inside your div is floating:
您可以使用的一种方法是浮动您的<p>元素,这将迫使它尽可能小,但如果您的 div 中的任何内容浮动,您将需要使用clearfix:
#two { float: left; }
Inline-block element
内联块元素
Inserting an inline element should work.
插入内联元素应该可以工作。
<p>content</p>
would become
会成为
<p><span>content</span></p>
Absolutely positioned element
绝对定位元素
Changing the element position to be absolute should also work:
将元素位置更改为绝对位置也应该有效:
#two { position: absolute; }
If you can't statically change the markup or the style, you can always change them dynamically through JavaScript.
如果您无法静态更改标记或样式,则始终可以通过 JavaScript 动态更改它们。
(absolutely positioned element)
(绝对定位的元素)
var realWidth = $("#two").css("position", "absolute").width();
(float)
(漂浮)
var realWidth = $("#two").css("float", "left").width();
(inline-block element)
(内联块元素)
var t = $("#two").html();
var realWidth = $("#two")
.empty()
.append($("<span>").html(t))
.width();
回答by noob
Apply word-wrap: break-word;to it.. so the word will break and there won't be any text going out of the container... btw you can't check the width of the text which is going out of the container.
应用word-wrap: break-word;到它......所以这个词会中断并且不会有任何文本从容器中流出......顺便说一句,你无法检查从容器中流出的文本的宽度。
Update:You can check if the width of text in it is bigger than the width of the container like this
更新:您可以检查是否在其文本的宽度是不是像容器的宽度更大此
回答by Sebbas
As others have pointed out, changing the positionof the element to absolutealso works.
Doing this will result in an inline-style which can mess with your css afterwards if you don't watch out. Here is a solution to get rid of the inline style again.
正如其他人指出的那样,position将元素的更改为absolute也有效。这样做会导致内联样式,如果您不注意,它会在之后弄乱您的 css。这是再次摆脱内联样式的解决方案。
//Change position to absolute
$('#two').css("position", "absolute");
var textWidth = $('#two').width();
//Get rid of the inline style again
$('#two').removeStyle("position");
//Plugin format
(function ($) {
$.fn.removeStyle = function (style) {
var search = new RegExp(style + '[^;]+;?', 'g');
return this.each(function () {
$(this).attr('style', function (i, style) {
return style.replace(search, '');
});
});
};
}(jQuery));
回答by will
The element itself is constrained to 200px, but the text inside spills out. If you insert a span (or any other inline element) inside the P tag it works fine.
元素本身被限制为 200 像素,但里面的文本会溢出。如果您在 P 标签内插入一个跨度(或任何其他内联元素),它工作正常。
http://jsfiddle.net/will/vv68y/5/
http://jsfiddle.net/will/vv68y/5/
Hope that helps :)
希望有帮助:)

