jQuery addClass如果图像高度大于宽度 [英] Jquery addClass if image height greater than the width

查看:134
本文介绍了jQuery addClass如果图像高度大于宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jquery addClass图片有一个疑问.

I have one question about jquery addClass image.

我正在Codepen的 演示 中尝试这种想法. io

I am trying this think in this DEMO from codepen.io

因此问题是,如果图像高度大于宽度,则javascript不会从图像中添加类.在这方面有人可以帮助我吗?

So the problem is the javascript is not adding class from the image if image height greater than the width. Anyone can help me in this regard ?

这是我的测试jquery代码:

This is my test jquery code:

$(document).ready(function() {
  var img = document.getElementById('.user_posted_image');
  //or however you get a handle to the IMG
  var width = img.clientWidth;
  var height = img.clientHeight;

  if(width < height){
     $('img').addClass('portrait');
  }
});

推荐答案

使用$(".user_posted_image")代替document.getElementById('.user_posted_image').您正在尝试通过 .classSelector 来获取商品.

Use $(".user_posted_image") instead of document.getElementById('.user_posted_image'). You are trying to get an item by .classSelector.

document.getElementById仅用于标识符,但是,如果您拥有jQuery库,则可以使用# idSelector 代替.另外,您可以利用 jQuery.width()

document.getElementById it is just for identifiers, But if you have the jQuery library, you can use #idSelector instead. Also, you can take advantage of jQuery.width() and jQuery.height() methods.

$(document).ready(function() {
  var img = $('#user_posted_image');//jQuery id selector

  var width = img.width(); //jQuery width method
  var height = img.height(); //jQuery height method

  if(width < height){
     img.addClass('portrait');
  }
});

<img id="user_posted_image" src="image.png" width="100" height="150" />

编辑(演示代码笔):您正在使用多张图片,应该使用 .each 方法引用所有元素,在第一个代码中仅在一个元素中起作用.

Edit (Demo CodePen): You are using multiple images, you should use the .each method to refer to all elements, in the first code only works in one element.

$(document).ready(function() {
  var imgs = $('.imgpreview');//jQuery class selector
  imgs.each(function(){
    var img = $(this);
    var width = img.width(); //jQuery width method
    var height = img.height(); //jQuery height method
    if(width < height){
       img.addClass('portrait');
    }else{
       img.addClass('landscape');
    }
  })
});

这篇关于jQuery addClass如果图像高度大于宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆