.outerWidth()返回不同视口大小的不同宽度

时间:2015-11-12 23:37:03

标签: javascript jquery html css outerwidth

我有一个水平滚动的图片库。包含所有图像的<div>通过总计所有子项的外宽度动态生成其宽度。

以下是图库的设置方式:

<div class="categoryImageArea">       
	<div class="categoryImage" onclick="window.location = 'http://localhost/kitkittle/product/test-1'">
		<img src="http://localhost/kitkittle/uploads/images/full/58172669e54ea075971494d6293444f5.jpg"><br> 
		<h3>Half Bubble -  $50.00</h3> 
	</div>
	<div class="categoryImage" onclick="window.location = 'http://localhost/kitkittle/product/bubble-mitosis'">
		<img src="http://localhost/kitkittle/uploads/images/full/23aacfda65e43671bede87bc18902b81.jpg"><br> 
		<h3>Bubble Mitosis -  $300.00</h3> 
	</div>
	<div class="categoryImage" onclick="window.location = 'http://localhost/kitkittle/product/bubble-on-water'">
		<img src="http://localhost/kitkittle/uploads/images/full/1e2dc5352f831ebacd3ccbb7a9b4717a.jpg"><br> 
		<h3>Bubble on Water -  $10.00</h3> 
	</div>
	<div class="categoryImage" onclick="window.location = 'http://localhost/kitkittle/product/bubble-on-water1'">
		<img src="http://localhost/kitkittle/uploads/images/full/69f7b2c3b640444dd5a23c3037c3cc84.jpg"><br> 
		<h3>Bubble on Ocean -  $210.00</h3> 
	</div>
	<div class="categoryImage" onclick="window.location = 'http://localhost/kitkittle/product/swimming-bubbles'">
		<img src="http://localhost/kitkittle/uploads/images/full/2d66a56b9f51f29ad5c6f58c82b2ab39.jpg"><br> 
		<h3>Swimming Bubbles -  $0.00</h3> 
	</div>
</div>

使用以下函数生成categoryImageArea的宽度:

function change(){
	if($(window).width() > 768){ 
		var width = 0; 
		$('.categoryImage').each(function(index, element){ 
			width += $(element).outerWidth(true); 
		}); 
		$('.categoryImageArea').width(width); 
	}
	else{ 
		$('.categoryImageArea').width('100%'); 
	} 
} 

当我的浏览器窗口最大化(1900 x 1280)时,这很有用: enter image description here

enter image description here

但是,当我的浏览器窗口大小只有一半时,它不起作用。 (对不起,截图很难看到 - 最后两个被推到下一行)。 enter image description here

我很困惑为什么会这样,所以我将change()函数(上面)alert作为width的值,因为它在两种情况下都为它添加了值。这很奇怪。

  • 大视口(好):0&gt; 984&gt; 1969年> 2953&gt; 3937&gt; 4921
  • 半视口(坏):0&gt; 656&gt; 1312> 1968年> 2624> 3280

所以我的问题是:由于我的浏览器视口不同,究竟是什么让$(element).outerWidth(true)的价值变得不同?

作为参考,应用于categoryImage的样式为:

.categoryImage {
    display: inline-block;
    margin: 2em;
    position: relative;
    cursor: pointer;
}

1 个答案:

答案 0 :(得分:0)

在.categoryImage上用display:left替换display:inline-block。然后。 categoryImageArea添加一类overflow:hidden或clearfix。

.categoryImage {
    float:left;
    margin: 2em;
    position: relative;
    cursor: pointer;
}