我实际上尝试在 JS 中获取图像的方向以向其添加类。它似乎在 Firefox 上运行良好,但我在其他浏览器上遇到问题。它在非常小的图像上效果更好,所以我想如果图像没有完全加载它就不会工作......但我找不到让它正常工作的解决方案! 谢谢!
我的代码:
$(document).ready(function() {
$('.gallery a').find('img').each(function() {
var imgClass = (this.width / this.height > 1) ? 'landscape' : 'portrait';
$(this).addClass(imgClass);
})
});
.gallery {
display: flex;
flex-wrap: wrap;
width: 450px;
}
.gallery a {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
overflow: hidden;
}
.gallery a img.landscape {
align-self: center;
height: 100%;
filter: sepia(100%);
}
.gallery a img.portrait {
align-self: center;
width: 100%;
filter: grayscale(100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery">
<a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
<img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
</a>
<a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
<img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
</a>
<a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
<img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
</a>
<a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
<img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
</a>
</div>
最佳答案
基本上,您需要先检查图像是否已加载,如果没有,则添加一个事件监听器来触发它。
您可以判断图像是否已加载,因为它的 width
和 height
将大于 0。如果它们等于 0,则不会加载。它可能在 FF 中工作,因为它正在缓存图像,所以它们会立即加载。
像这样的东西应该可以解决问题:
function setImageClass(img) {
var imgClass = (img.width / img.height > 1) ? 'landscape' : 'portrait';
$(img).addClass(imgClass);
}
$(document).ready(function() {
$('.gallery a').find('img').each(function() {
if (this.width > 0) {
setImageClass(this);
} else {
$(this).once('load', function () {
setImageClass(this);
});
}
})
});
关于javascript - 获取图像 JS 的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44678926/