我一直在尝试编写一个函数,将所有行的子元素设置为具有特定类("匹配高度")的高度相同。到目前为止它工作正常,但调整大小的错误,通常是实际最高的元素将比缩放浏览器后的其他元素短。这是迄今为止的代码。
function matchHeights(wrapper) {
//get all the elements with the "wrapper" clas
var match_height_elements = document.getElementsByClassName(wrapper);
//count the elements
var match_height_count = match_height_elements.length;
//my tallest
var my_tallest = 0;
//iterate through the "wrapper" elements
for (var i = 0; i < match_height_count; i++) {
//get the children of the wrapper elements
var children = match_height_elements[i].children;
//count the children
var child_count = children.length;
//iterate through the child elements
for (var j = 0; j < child_count; j++) {
//get the childs height
var child_height = children[j].offsetHeight;
//if taller than my_tallest then
if (child_height != null && child_height > my_tallest) {
my_tallest = child_height;
}
}
//iterate through the child elements
for (var k = 0; k < child_count; k++) {
//if height less than tallest
if (children[k].offsetHeight < my_tallest) {
//set child height to tallest
children[k].style.height = my_tallest + 'px';
}
}
}
}
window.onload = matchHeights('match-heights');
window.addEventListener("resize", matchHeights);
&#13;
<div class="match-heights">
<div>text</div>
<div>much longer text Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin semper libero vel maximus tincidunt. Fusce lacus nisl, rhoncus vel nisi aliquam, egestas hendrerit tortor. Etiam eget luctus ex. Curabitur sed mi condimentum, vehicula ante non, scelerisque tellus. Duis risus magna, volutpat a suscipit et, aliquam volutpat lacus. Vivamus at magna ut tortor bibendum egestas vitae nec libero. Aliquam iaculis pretium volutpat. </div>
</div>
&#13;
解决!下面nalply说得对。我为resize事件添加了一点延迟并修复了它。
我改变了
window.addEventListener("resize", matchHeights);
到
function matchHeightsDelay(){
setTimeout(matchHeights('match-heights'), 10);
}
window.addEventListener("resize", matchHeightsDelay);
如果有其他人有办法改善这一点,请告诉我。