我正在尝试让jQuery使用类“image”找到div中图像的高度/宽度属性,然后将这些值作为css应用到具有“overlay”类的div,该类是“子”图片”。下面的代码是我到目前为止所得到的。它适用于“图像”的一个实例。但我不知道如何让它通过“图像”的每个实例并将正确的值应用于“叠加”。我和.each一起玩,但我无法让它工作。
HTML:
<div class="image">
<img src="some-img" width="400" height="200" />
<div class="overlay"></div>
</div>
jQuery的:
var height = $("img").attr("height");
var width = $("img").attr("width");
$(".overlay").css({
height: height,
width: width
});
提前致谢!
答案 0 :(得分:3)
$(".image").each(function(index, el) {
var $img = $("img", this); // equivalent: $(this).find("img")
$(".overlay", this).css({
height: $img.attr("height"),
width: $img.attr("width")
});
});
您还可以迭代img
元素本身并使用.next()
获取相应的叠加层。
答案 1 :(得分:2)
我建议:
$('.image img').each(
function(){
var that = $(this),
h = that.height(),
w = that.width();
that.next().css({ 'height' : h, 'width' : w });
});