我正试图给我的图像一个风景或肖像类在一个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" );
}
});
});
null
$(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>