选择列表的最高图像

时间:2011-11-22 17:26:44

标签: jquery image jquery-selectors

使用jQuery选择列表中最高图像的最简单方法是什么?

结构:

<ul class="gallery">
    <li><img width="100px" height="300px" src="1.jpg"></li>
    <li><img width="100px" height="200px" src="2.jpg"></li>
    <li><img width="100px" height="500px" src="3.jpg"></li>
</ul>

2 个答案:

答案 0 :(得分:5)

// use anonymous function to prevent clutter of the scope
(function() {
    var max_height = 0;
    var image = null;

    $('.gallery li img').each(function() {
      var cur_height = $(this).height();
      if (cur_height > max_height) {
          max_height = cur_height;
          image = this;
      }
    });

    // just an example
    $(image).addClass('tallest');
})();

答案 1 :(得分:3)

var height = 0, 
    img = null;
$('img','.gallery').each(function() {
    var h = $(this).height();
    if (h > height) {
        height = h;
        img = this;
    }
});

// img is the tallest image