动态元素高度不会单独影响所有实例



我写了一些jQuery,它在父级具有.four-three-img类的img元素上动态设置4:3的纵横比高度。它按预期工作,除非单个页面包含不同宽度的.four-three-img元素。

例如,如果存在两个包含.four-three-img img元素的sections,则它将确定第一section内的第一img的高度,并将其应用于第一和第二section元素中的剩余imgs,其可以更小或更大。我试着把脚本放在for循环中,但没有什么区别。

这是脚本:

$(window).on('load resize', function() {
var fourThreeHeight = $('.four-three-img').width() * 0.75;
$('.four-three-img img').each(function() {
$(this).height(fourThreeHeight);
});
});

演示:http://codepen.io/ourcore/pen/apWjmg

尝试将fourThreeHeight-变量放入each-函数中,并将$('.four-three-img')更改为$(this):

$(window).on('load resize', function() {
$('.four-three-img img').each(function() {
var fourThreeHeight = $(this).width() * 0.75;
$(this).height(fourThreeHeight);
});
});

将其置于each-函数之外将导致只存储第一个元素的宽度,而不存储每个元素。

实时代码笔

最新更新