2011-11-21 82 views
3

我有一个水平滚动的网站,它有一个与id = "bookWrap"的div,填充了inline-block元素,所以宽度对我来说是未知的,但它远远延伸了我的viewPort。jQuery获取大于视口的元素的宽度

虽然试图通过$('#bookWrap').width()获取此元素的宽度jQuery返回我的视口宽度是1680,而不是元素的实际宽度。

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

+0

请给我们http://jsfiddle.net或一些源代码 –

+0

@omnosis在这里你去http://jsfiddle.net/szKkT /,请注意当您调整警报更改的输出窗口大小时。 –

回答

0

也许你应该计算宽度:

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

这里看看:http://jsfiddle.net/szKkT/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

+0

这对我有用,但我不得不这样做:'$(selector).children()。each(..)' – ndsc

+1

@ndsc这是因为Rory在选择器中传递给孩子,而不仅仅是外部元素。 – krillgar

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

您可以使用元素scrollWidth属性:

var realWidth = document.getElementById('#bookWrap').scrollWidth;