gpt4 book ai didi

javascript - JQuery获取子元素的最高高度并放入父元素

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:56 25 4
gpt4 key购买 nike

previous question 中,我在个人身上设置了平等的高度<li>页面上来自 UL 组的标签。但是现在我意识到为了更好的主题化,我想在一组 <li> 上设置最高的高度。 UL 组中的标签并将其设置为其各自的父级 <ul>本身专门用于更好地主题化我的页面。我有 a new fiddle在这里我试图找到 <li> 的最高高度在 UL 组内并将其设置为 UL。

问题仍然是特异性。 <li>的最高高度来自第一个 UL 组的设置为所有 <ul>页面上的标签。最高的高度<li> UL 组(第 1 行)中的高度为 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...

Working version基于 this one下面

最佳答案

如果我没理解错的话,你应该在 .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);
});

关于javascript - JQuery获取子元素的最高高度并放入父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13332833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com