找出图像是水平还是垂直

cla*_*ras 1 jquery image width

我有多个图像,想要找出每个图像是水平还是垂直,并添加一个类,所以我可以相应地设置它.

我尝试了很多东西,包括这样的东西:

if ($(".img").width() > $(".img").height()) {
$(this).addClass("horizontal");
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢!

Sha*_*oli 13

你的代码因为没有用$(this).this这里没有指向图像元素,但它指向范围的最新实例.

试试这将使用jQuery each循环遍历所有图像元素,然后有条件地添加所需的类.

$("img").each(function(){
    var $this = $(this);
    if ($this.width() > $this.height()) {
        $this.addClass("horizontal");
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您有一个".img"所有图像元素的类,那么您可以使用类选择器.

$(".img").each(function(){
    var $this = $(this);
    if ($this.width() > $this.height()) {
        $this.addClass("horizontal");
    }
});
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用jQuery filter方法过滤宽度大于高度的所有图像,然后一次添加所需的类.

$(".img").filter(function()
    var $this = $(this);
    return $this.width() > $this.height();
}).addClass("horizontal");
Run Code Online (Sandbox Code Playgroud)

.filter() - 将匹配元素集减少到与选择器匹配的元素或通过函数测试.

如果您在页面加载时执行此操作,请确保在窗口加载事件中执行此代码,这将确保加载所有图像.

$(window).load(function(){
     $(".img").each(function(){
        var $this = $(this);
        if ($this.width() > $this.height()) {
            $this.addClass("horizontal");
        }
     });
});
Run Code Online (Sandbox Code Playgroud)