我正在使用
jQuery(document).ready(function() {
jQuery("img").each(function() {
// Calculate aspect ratio and store it in HTML data- attribute
var aspectRatio = jQuery(this).width()/jQuery(this).height();
jQuery(this).data("aspect-ratio", aspectRatio);
// Conditional statement
if(aspectRatio > 1) {
// Image is landscape
jQuery( this ).addClass( "landscape" );
} else if (aspectRatio < 1) {
// Image is portrait
jQuery( this ).addClass( "portrait" );;
} else {
// Image is square
jQuery( this ).addClass( "square" );;
}
});
});
但它每次都只是返回景观。
我想要做的就是为肖像图像创建一个类,这样我就可以使用 CSS 将它们并排设置为 50% 宽度,而横向图像为 100% 宽度。
最佳答案
我无法发表评论,因为声誉太低,但我认为您的错误可能来自于您在 $(document) 上执行
而不是 .each()
。 ready()$(window).load()
$(document).ready()
等待 DOM 操作安全,但不等待所有图像和其他内容加载。
$(window).load()
在执行前等待所有内容加载完毕
它们很可能都是横向显示的,因为它们很短(只有 alt 文本高度)但很长(alt 文本宽度)
关于javascript - 在 jquery 中找到图像方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54300367/