如何解决测量图像的宽度和高度在 Chrome 和 Firefox 中返回 0,但在 Safari 中有效
我正在尝试通过在加载时测量图像的尺寸,为我的图像在 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()
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。