如何与jQuery找到最短的div


<div id="c1" class="features" style="height:100px;width:100px;"></div>
<div id="c2" class="features" style="height:120px;width:100px;"></div>
<div id="c3" class="features" style="height:90px;width:100px;"></div>
<div...> 

如何使用jQuery找到最短的div

例如,以上将导致Div ID =" C3",因为其高度为90px。

var shortest = [].reduce.call($(".features"), function(sml, cur) {
    return $(sml).height() < $(cur).height() ? sml : cur;
});

这是如何做没有 jquery的方法:

var allDivs = document.getElementsByTagName("div");
var min = 0;
var element;
for (var i = 0; i < allDivs.length; i++) {
    if (allDivs[i].className == "features") {
        if (allDivs[i].offsetHeight < min) {
            min = allDivs[i].offsetHeight;
            element = allDivs[i];
        }
    }
}
alert(element);

使用jQuery .height()方法,该方法返回元素的计算高度值。

var candidates = getSetOfDivs();
var smallest = candidates[0];
$( candidates ).each( function(e, i) {
    if( $(e).height() > smallest.height() ) smallest = $(e);
} );

您真的想要最小的吗?还是您只想要高度最低的那个?那是不同的事情。这是一个逐个区域找到最小的解决方案(但是您可以通过用$(this).height() * $(this).width()替换CC_3来使其高度进行。

var divs = $('.features');
var smallest;
var smallestarea = null;
$('.features').each(function () {
  var thisarea = $(this).height() * $(this).width();
  if (smallestarea === null || thisarea < smallestarea) {
    smallest = $(this);
    smallestarea = thisarea;
  }
});
document.write(smallest.attr('id'));

http://jsbin.com/ufujiy/1/edit

const targets = ['.div1', '.div2', '.div3'];    
const shortest = targets.reduce((sml, cur) => ($(sml).height() < $(cur).height()) ? sml : cur);

最新更新