[英]How to make change the height of all images inside a div?
How to make change the height of all images inside a div? 如何更改div中所有图像的高度?
I have 我有
$('.images img').each(function() {
$('img').attr('height', element.parent().attr('imgheight'));
});
<div imgheight="300px" class="images">
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/goldenhorseman.jpg " />
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/bronze-horseman.jpg " />
</div>
It does not seem to do anything - see https://jsfiddle.net/yu51a5/527gn64n/4/ . 它似乎没有任何作用-请参阅https://jsfiddle.net/yu51a5/527gn64n/4/ 。 How to make it work? 如何使其运作?
I cannot use "height=100%" because normally these images come with captions, so the image should be shorter that the div. 我不能使用“ height = 100%”,因为通常这些图像带有字幕,因此图像应比div短。
You haven't defined element
. 您尚未定义element
。 Access the node from inside the each function. 从每个函数内部访问节点。
$('.images img').each(function(i, node) {
$('img').attr('height', $(node).parent().attr('imgheight'));
});
I suggest you to use HTML5 data- attribute with your custom attribute imgheight
我建议您将HTML5数据属性与自定义属性imgheight
<div data-imgheight="300px" class="images">
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/goldenhorseman.jpg " />
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/bronze-horseman.jpg " />
</div>
And JS can be as easy as this: JS可以像这样简单:
$('.images > img').css('height', $('.images').data('imgheight'));
But, if you have multiple .images
div, you would do like this 但是,如果您有多个.images
div,您会这样做
$('.images img').each(function() {
$(this).css('height', $(this).closest('.images').data('imgheight'));
});
or better 或更好
$('.images').each(function() {
$(this).find('img').css('height', $(this).data('imgheight'));
});
Change element
to $(this)
and you're good. 将element
更改为$(this)
就可以了。
https://jsfiddle.net/wh85afq7/ https://jsfiddle.net/wh85afq7/
Change the 2 references within the each function to the images to $(this)... 将每个函数中的2个引用更改为图像$(this)...
$('.images img').each(function() {
$(this).css('height', $(this).parent().attr('imgheight'));
});
You can use data-height
attribute and get value by element.data("height")
您可以使用data-height
属性并通过element.data("height")
获取值
here is the working example below 这是下面的工作示例
$( document ).ready(function() { $('.images img').each(function() { $(this).attr('height',$('.images').data("height")); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-height="300px" class="images"> <img src="http://www.yu51a5.com/wp-content/uploads/2015/01/goldenhorseman.jpg" /> <img src="http://www.yu51a5.com/wp-content/uploads/2015/01/bronze-horseman.jpg" /> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.