我编写了一个函数来更改图像加载时元素的高度:
$(document).ready(function () {
$("img").load(function() {
var width = $(this).width();
$(".item").height(width*0.85);
});问题是,当我重新加载我的页面时,它有时工作,有时不工作。只是随机性地改变了高度,有时不改变。我怎样才能让它一直工作?
html:
<div class="row row-10 items-grid">
<div class="col-md-4 col-xs-6">
<a class="item">
<img src="/get/2" alt="">
<div class="overlay">
<h2 class="">Dogs</h2>
</div>
</a>
</div>
<div class="col-md-4 col-xs-6">
<a class="item" >
<img src="/get/3" alt="">
<div class="overlay">
<h2 class="uppercase">Cats</h2>
</div>
</a>
</div>
</div>发布于 2020-03-23 22:51:25
您可以尝试循环所有图像,然后分别向每个图像添加图像onload事件,当每个图像加载完成后,您可以更新最接近图像的元素的高度,而不是一次更新所有.item元素,例如:
$(document).ready(function() {
$('img').each(function() {
var $this = $(this);
var img = new Image();
img.onload = function() {
var width = $(this).width();
$this.closest(".item").height(width * 0.85);
};
img.src = $(this).attr('src');
});
});https://stackoverflow.com/questions/60815692
复制相似问题