问题描述
我正在尝试通过在加载时测量图像的尺寸,为我的图像在 wordpress 图像库中提供横向或纵向类。该代码在 Safari 中有效,但 Firefox 返回 0 像素的宽度和高度,Chrome 有时会正确加载它们,有时则不会。我很困惑,有人可以帮我吗?
jQuery(window).on('load',function () {
jQuery(".blocks-gallery-grid img").each(function() {
var aspectRatio = jQuery(this).css('width','auto').width()/jQuery(this).css('height','auto').height();
console.log(jQuery(this).attr('src'));
console.log(jQuery(this).width());
console.log(jQuery(this).height());
jQuery(this).data("aspect-ratio",aspectRatio);
if(aspectRatio > 1) {
jQuery(this).parent().parent().parent('li').addClass( "landscape" );
} else if (aspectRatio < 1) {
jQuery(this).parent().parent().parent('li').addClass( "portrait" );
} else {
jQuery(this).parent().parent().parent('li').addClass( "landscape" );
}
});
});
解决方法
$(window).on('load',function() {
$(".blocks-gallery-grid img").each(function() {
let _this = $(this),aspectRatio = _this.width()/_this.height(),parentLi = _this.closest('li');
if(aspectRatio > 1) {
parentLi.addClass( "landscape" );
} else if (aspectRatio < 1) {
parentLi.addClass( "portrait" );
} else {
parentLi.addClass( "landscape" );
}
});
});
img{
max-width: 100%;
}
li{
padding: 15px;
box-sizing: border-box;
border: 3px solid;
}
.landscape{
border-color: red;
}
.portrait{
border-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="blocks-gallery-grid">
<li>
<img src="https://dummyimage.com/600x400/000/fff">
</li>
<li>
<img src="https://dummyimage.com/400x600/000/fff">
</li>
</ul>
你能不能试试这样的:
$(window).on('load',function () {
$(".blocks-gallery-grid img").each(function() {
let _this = $(this);
let aspectRatio = _this.width()/_this.height();
_this.data("aspect-ratio",aspectRatio);
if(aspectRatio > 1) {
_this.parent().parent().parent('li').addClass( "landscape" );
} else if (aspectRatio < 1) {
_this.parent().parent().parent('li').addClass( "portrait" );
} else {
_this.parent().parent().parent('li').addClass( "landscape" );
}
});
});
此外,我假设 li
是该元素的唯一列表项父项,因此您可以省略所有 .parent()
选择器并使用:.closest()
。