我写了一些jQuery,它在父级具有.four-three-img
类的img
元素上动态设置4:3的纵横比高度。它按预期工作,除非单个页面包含不同宽度的.four-three-img
元素。
例如,如果存在两个包含.four-three-img img
元素的section
s,则它将确定第一section
内的第一img
的高度,并将其应用于第一和第二section
元素中的剩余img
s,其可以更小或更大。我试着把脚本放在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
-函数之外将导致只存储第一个元素的宽度,而不存储每个元素。
实时代码笔