jQuery检测div中多个图像的图像尺寸

时间:2013-10-09 02:32:48

标签: javascript jquery html

我有这个jQuery:

jQuery(".storyImg").each(
function(){
    if(this.width() > this.height()){
        jQuery(this).addClass("landscape");
    } else if (this.width() < this.height()){
        jQuery(this).addClass("portrait");
    } else {

    }
}
);

它似乎不起作用。我甚至无法从函数内部发出警报。它肯定包含在html文件中,而类.storyImg绝对是正确的。

3 个答案:

答案 0 :(得分:1)

内部each回调this是指没有widthheight方法的dom元素,您需要在jQuery包装器中调用这些方法元件

jQuery(".storyImg").each(function () {
    var $this = jQuery(this)
    if ($this.width() > $this.height()) {
        $this.addClass("landscape");
    } else if ($this.width() < $this.height()) {
        $this.addClass("portrait");
    } else {

    }
});

答案 1 :(得分:0)

您需要执行jQuery(this).width()jQuery(this).height(),因为this不是jQuery对象。您的控制台应该有错误。您只需要在this上调用jQuery一次。

您还应该等待$(window).load()中的此操作,因为您要等待图片加载。

jQuery(".storyImg").each(function(){
  var $this = jQuery(this);
  if($this.width() > $this.height()){
    $this.addClass("landscape");
  } else if ($this.width() < $this.height()){
    $this.addClass("portrait");
  } else {

  }
});

答案 2 :(得分:0)

没有js guru但是你不能打电话给this.width()。就像你已经在那里使用jQuery(this).width()一样。最好还是将它添加到var:

var $this = jQuery(this);
if($this.width() > $this.height()){
  // blah
}