[英]HTML, jQuery, CSS - Width() returning entire page width instead of div on page load?
所以我试图让一个函数在加载页面时在div中应用“ padding-bottom”,唯一的问题是宽度返回整个文档值而不是div值。 当我使用另一个功能(在图像之间更改)时,该功能可以正常工作。
$(window).load(function () {
$('.photoset').each(function () {
$items = $(this).find('img')
function get_height(target) {
return (($items.eq(target).height() / $(this).width()) * 100) + '%';
}
$items.css({ paddingBottom: get_height(0) });
});
}
Css如下:
.photowrapper{
width:60%;
margin:auto;
}
.photoset {
position: relative;
display: block;
margin:auto;
overflow:hidden;
}
.photoset figure{
width: 100%;
margin: 0;
padding: 0;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
text-align:center;
}
.photoset img {
opacity: 0;
transition:opacity 1.2s;
max-width:100%;
}
.photoset .photoset-show img{
opacity: 1;
}
和HTML
<div class="photowrapper">
<div class="photoset center-block">
<figure class="photoset-show">
<img src="/images/5220a574-77a8-4aa6-aecc-aedf60eed6e2.jpg" />
</figure>
<figure class="">
<img src="/images/9e59af1e-de75-4ddb-b091-f816224d9f6e.jpg" />
</figure>
<figure class="">
<img src="/images/ad76e5e3-5780-4f22-bcb4-8106fc41161a.jpg" />
</figure>
</div>
</div>
此函数按预期工作,在图像之间切换时返回正确的宽度值:
var showCurrent = function (photoset) {
$items = photoset.find('figure');
$images = photoset.find('img');
var counter = photoset.data('counter');
var numItems = $items.length;
var itemToShow = Math.abs(counter % numItems);
$items.each(function () {
$(this).removeClass('photoset-show');
})
function get_height(target) {
return (($images.eq(target).height() / photoset.width()) * 100) + '%';
}
photoset.animate({ paddingBottom: get_height(itemToShow) }, 400);
$items.eq(itemToShow).addClass('photoset-show');
};
this
不是您认为在get_height()
内部的get_height()
。 函数内部具有不同的上下文。 存储this
的引用或将其作为参数传递
尝试
$(window).load(function () {
$('.photoset').each(function () {
var $photoset = $(this), $items = $photoset.find('img')
function get_height(target) {
return (($items.eq(target).height() / $photoset.width()) * 100) + '%';
}
$items.css({ paddingBottom: get_height(0) });
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.