jQuery获取大于视窗的元素宽度

4

我有一个水平滚动的网站,其中有一个带有id="bookWrap"的div,里面填充了inline-block元素,因此宽度对我来说是未知的,但它远远超出了视口。

当我尝试通过$('#bookWrap').width()来获取该元素的宽度时,jQuery返回的是我的视口宽度,即1680,而不是元素的实际宽度。

我该如何获取延伸到视口之外的元素的真实宽度?


请提供一个 http://jsfiddle.net 或一些源代码。 - Gergely Fehérvári
@omnosis 这是链接 http://jsfiddle.net/szKkT/ ,请注意当您调整输出窗口大小时,警报会发生变化。 - George Reith
4个回答

2
考虑这更像是一种解决方法,因为似乎jQuery的width()outerWidth()都在某种程度上截断了视口宽度。
alert(getTotalWidth("#bookWrap DIV"));

function getTotalWidth(selector) {
    var totalWidth = 0;
    $(selector).each(function() {
        totalWidth += $(this).outerWidth();
    });
    return totalWidth;
}

Fiddle here


这对我有用,但我必须这样做:$(selector).children().each(..) - ndsc
1
@ndsc 这是因为Rory传递了子元素的选择器,而不仅仅是外部元素。 - krillgar

2
您可以使用元素的scrollWidth属性:
var realWidth = document.getElementById('#bookWrap').scrollWidth;

0
您可以使用此片段检查哪些元素大于您的视口:

$('*').each(function () {
   var viewportWidth = 768;
   if($(this).outerWidth() > viewportWidth ){
     //prints element in console so you can check what's the element
     console.log($(this)[0]); 
   }
});


0

也许你应该计算宽度:

var width = 0;
$('#bookWrap div').each(function(){
   width += $(this).width();
});
alert(width);

看这里:http://jsfiddle.net/szKkT/4/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接