添加 class 如果宽度 > 高度,jQuery

add class if width > height, jQuery

我正在尝试将 class 添加到画廊中的所有高图片中。那为什么它不起作用?

这是我的代码:

var boxImg = $('.boxImg img');
var boxImgW = boxImg.width();   
var boxImgH = boxImg.height();

boxImg.each(function(){ 
    if (boxImgW < boxImgH) {
        this.addClass('tallImg');
    }
});

执行顺序很重要,.width().height() 应用于一组匹配元素时,会为您提供集合中第一个元素的度量。因此,采取的做法是:

var boxImg = $('.boxImg img');
boxImg.each(function() {
    //this refers to the current element you're iterating through.
    var boxImgW = $(this).width();   
    var boxImgH = $(this).height();
    if (boxImgW < boxImgH) {
        //you almost had it right here :-)
        $(this).addClass('tallImg');
    }
});

好吧,我要么你的问题有误,要么你的代码是因为你要求 if(width>height) 而不是应用 css 但在你的代码中你做的是相反的(宽度