繁体   English   中英

JQuery获得最高的孩子身高并放入父元素

[英]JQuery get tallest height of child and put into parent element

在上一个问题中 ,我在页面上的UL组中为单个<li>标签设置了相等的高度。 但是现在我意识到为了更好的主题,我想在UL组中的一组<li>标签上设置最高的高度,并将其设置为其各自的父<ul>本身,以便更好地理解我的页面。 我在这里有一个新的小提琴 ,我试图在UL组中找到<li>的最高高度并将其设置为UL。

问题仍然是特异性。 来自第一个UL组的<li>的最高高度被设置为页面上的所有<ul>标签。 UL组(第1行)中最高<li>的高度为260px,第2行的高度为156px。 但是,仍然会在页面上的两个UL标签上设置260px。 UL将在页面上增长,因此我希望代码是可扩展的,而无需在JQuery中指定每一行。 到目前为止,我试过这个:

// get the height of the tallest LI within each UL group
    var max = Math.max.apply(Math, $(".item-list ul li").map(
        function(){
          return $(this).height();
        }
      ));

// now render the height in each parent UL

    $(".item-list ul").each(function() {
      $(this).find(".item-list ul").height(max);
    });

......但第二部分不起作用。 这有效但......

$(".item-list ul").height(max);

...它将最高<li>的高度放在所有UL标签的页面上。 理想情况下,最终的HTML应该是:

<div class="item-list row-1">
<ul style="height: 260px;">
etc...

<div class="item-list row-2">
<ul style="height: 156px;">
etc...

基于以下这个的 工作版本

如果我理解正确,你应该在.each()循环中执行max操作。

function thisHeight(){
    return $(this).height();
}

$(".item-list ul").each(function() {
    var thisULMax = Math.max.apply(Math, $(this).find("li").map(thisHeight));
    $(this).height(thisULMax);
});

我还将map函数设置为命名函数,以便您可以重用它。


以下是一些更清洁的解决方案。

这个函数将函数传递给height()以将其用作迭代器。 稍微缩短一点。

function thisHeight(){
    return $(this).height();
}

$(".item-list ul").height(function() {
    return Math.max.apply(Math, $(this).find("li").map(thisHeight));
});

这是使用.reduce()的另一种方式,虽然IE8需要垫片以及更低。

function maxHeight(max, elem) {
    var h = $(this).height();
    return max > h ? max : h;
}

$(".item-list ul").height(function() {
    return $(this).find("li").toArray().reduce(maxHeight, 0);
});

好像很复杂?

$(".item-list ul").each(function(idx, elm) {
     var LIheight = 0;
     $('li', elm).each(function() {
         if ($(this).height() > LIheight) LIheight = $(this).height();
     }).height(LIheight);
});

由于你有两个<ul>类'.item-list'标签,为什么不试试这个:

$(".item-list ul").eq(0).height(max);

这只会为HTML中的第一个标记设置高度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM