javascript - 在 jquery 中找到图像方向?

标签 javascript jquery css wordpress

我正在使用

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/

相关文章:

javascript - 错误 [Vue 警告] : v-bind without argument expects an Object or Array value

javascript - 使用 Jquery 检测选择列表的更改

css - IE css - 最后一个表格行要扩展以填充剩余高度

html - 固定元素在视差元素内滚动

javascript - Material UI(日期时间选择器): Invalid Date Format message after submission

javascript - 网页包 - 'velocity is not defined'

javascript - 使用 React Router,我如何为 HTML 元素分配一个类?

javascript - 复选框检查 td 内嵌套复选框的所有同级

php - onchange 下拉列表动态设置最大值 yii CMultiFileUpload

html - 展开高度CSS