在jquery中找到图像方向?

SGP*_*coe 1 javascript css wordpress jquery

我正在使用

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" );;            
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

但它每次都只是回归景观.

我想做的就是有一个肖像图像类,所以我可以使用CSS使它们50%宽度并排,而景观图像是100%宽度.

wit*_*oux 6

我无法评论,因为信誉太低,但我认为你的错误可能来自一个事实,即你做你.each()$(document).ready(),而不是$(window).load()

$(document).ready() 等待DOM操作安全,但不等待加载所有图像和其他内容.

$(window).load() 在执行之前等待加载所有内容

它们很可能都是景观,因为它们很短(只有替代文字高度)但很长(替代文字宽度)