javascript - 获取图像 JS 的方向

标签 javascript jquery html css browser

我实际上尝试在 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>

最佳答案

基本上,您需要先检查图像是否已加载,如果没有,则添加一个事件监听器来触发它。

您可以判断图像是否已加载,因为它的 widthheight 将大于 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/

相关文章:

php - 来 self 的数据库的每日报告

javascript - 将 js 变量传递给 onkeyup 输入文本

javascript - Phonegap 后退按钮我 android 没有捕获

javascript - setTimeout 不等待 JQuery Mobile 中的指定时间间隔

javascript - Vuex 在组件中获取突变后的状态

javascript - 在指定范围内覆盖 document.write?

javascript - 将选择的选项值从一种表单复制到另一种表单

javascript - 在 jQuery UI sortable 中,如何获取拖动元素下方的元素

javascript - 更改指针事件 : none due to if-statement, 嵌套时出现问题

javascript - 在鼠标悬停时调出部分图像