jQuery 函数没有使用变量

标签 jquery css image variables

我在 stackoverflow 上找到了一个代码来检查图片是纵向还是横向,并添加 css 宽度和高度格式。

在让它工作之后(因此到处都是 $LSC),我发现它立即跳转到“else”,并且只输出那个结果。 (所有图像的宽度自动和高度 100%)

我的问题是,我应该在代码中更改什么才能使其工作并真正比较宽度和高度?

var $LSC = jQuery.noConflict();

$LSC(document).ready(function(){

    $LSC(".pg-cat-image").each(function(){    
        var real_width = $LSC(this).width();
        var real_height = $LSC(this).height();
        var parentwidth = $LSC(this).parent().width();
        var parentheight = $LSC(this).parent().height();

        var ratioParent = parentwidth / parentheight;
        var ratio = real_width / real_height;    

        if (ratioParent < ratio) {        
            $LSC(this).css({'width' : '100%', 'height' : 'auto'});
        }else{
            $LSC(this).css({'width' : 'auto', 'height' : '100%'});
        }
    });

});

最佳答案

我不明白你为什么要涉及父容器。不能只比较图像的宽度和高度吗?

var $LSC = jQuery.noConflict();

$LSC(document).ready(function(){

    $LSC(".pg-cat-image").each(function(){    
        var real_width = $LSC(this).width();
        var real_height = $LSC(this).height();  

        if (real_width > real_height) {        
            // The image is landscape
        } else if (real_width < real_height) {
            // The image is portrait
        } else {
            // The image is square
        }
    });
});

关于jQuery 函数没有使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853542/

相关文章:

php数组下拉字段未插入数据库mysql

javascript - Jquery setTimeout 不起作用(图像幻灯片)

java - 如何使 java 的 ImageBuffer 正确读取 PNG 文件?

php - 无法识别文件目录路径的变量

c# - 在 RTF 中提取嵌入的图像对象

javascript - jwplayer:使用 seek()、onTime() 和 stop() 播放部分视频

javascript - 当固定 DIV 滚动到另一个 HTML 元素时动态添加 CSS 类

html - 使文本在重叠的 div 上方可见

javascript - 最小化到一定宽度后显示: inline-block,,停止inline-block,保持结构不变

css - 左对齐和右对齐在同一行上的跨浏览器 CSS