gpt4 book ai didi

javascript - 如何使用 JavaScript 使每个 div 的高度相等?

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:07 24 4
gpt4 key购买 nike

我正在尝试创建一个对象来确定一组元素的最高高度,并使每个元素与最大元素的高度相匹配。

在这个对象中,我试图将一个选择器传递给驻留在我的对象方法内部的 JQuery 方法。不幸的是,我无法通过这种方式获取每个元素,并且我的 Each 语句不会触发,但该对象返回 0 个元素。

下面是我的对象的一个​​例子:

var heightBalance = {
containerName: '',
childElements: '',
alert: function() {
var divs = $(this.childElements);
console.log(divs);
$.each(divs, function(index, value) {
console.log('working');
});

}
}

heightBalance.containerName = '#containers';
heightBalance.childElements = 'div';
heightBalance.alert();
#one {
background-color: green;
width: 50px;
height: 200px;
}
div {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="containers">
<div id="one">d</div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
</div>

最佳答案

在呈现 div 之前,您的脚本在头部进行了初始化。将脚本移动到正文末尾,或使用 jQuery 就绪函数 ( fiddle ):

$(function () {
var heightBalance = {
containerName: '',
childElements: '',
alert: function () {
var divs = $(this.childElements);
console.log(divs);
$.each(divs, function (index, value) {
console.log('working');
});

}
}

heightBalance.containerName = '#containers';
heightBalance.childElements = 'div';
heightBalance.alert();
});

answer中的代码会给你你想要的相同高度:

$(function() {
// Get an array of all element heights
var elementHeights = $('.features').map(function() {
return $(this).height();
}).get();

// Math.max takes a variable number of arguments
// `apply` is equivalent to passing each height as an argument
var maxHeight = Math.max.apply(null, elementHeights);

// Set each height to the max height
$('.features').height(maxHeight);
});

关于javascript - 如何使用 JavaScript 使每个 div 的高度相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868527/

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