更新时间:2023-02-11 22:16:17
当隐藏元素时,它们的宽度可能会有所不同你的造型。当隐藏元素位于另一个隐藏元素中时,结果可能会再次变化。但是,Jquery代码非常简单:
$('#foo')。parent()。width()
这将抓住foo的父div,然后抓住它的宽度,但我无法保证它会获得元素的无遮挡的自然宽度。希望有所帮助!
1.4.4 return size of hidden element, but what about element in another hidden element? Is there any better solution then getWidth?
<script type="text/javascript">
function getWidth(element){
var parent = element.parent();
$('body').append(element);
var width = element.width();
parent.append(element);
return width;
}
$(function(){
var width = $("#foo").width();
console.log(width); //0
width = getWidth($("#foo"));
console.log(width); //ok
});
</script>
<div style='display:none'>
<div style='display:none' id='foo'>bar</div>
</div>
When elements are hidden, their width may vary depending on your styling. And when a hidden element is inside another hidden element, results could vary again. However, the Jquery code is quite straightforward:
$('#foo').parent().width()
This will grab foo's parent div, then grab its width, but I can't guarantee it will get the element's unhidden natural width. Hope that helps!