【发布时间】:2015-07-28 22:03:04
【问题描述】:
嘿,所以我发现了 CSS-tricks Chris Coyier 的这个甜蜜的 jquery sn-p,它将在页面上共享相同顶部位置(在同一行上)的 div 元素高度重置为最高元素。
问题 此解决方案几乎适用于流体宽度布局,并在顶部位置更改时重置高度,但在页面首次加载时将其重置为行中当前最高元素的原始高度。这是一个问题,因为自从首次加载此页面以来,由于使用了相对单位(如 ems)或由于段落自动换行,最高元素的高度可能已经发生了变化。 建议的解决方案 解决方案是将行元素的高度设置为最高元素的当前高度,而不是原始高度。我没有成功。
这里是 sn-p,其中“li.half”是被比较和调整大小的元素。
jQuery(document).ready(function($) {
// these are (ruh-roh) globals. You could wrap in an
// immediately-Invoked Function Expression (IIFE) if you wanted to...
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array();
function setConformingHeight(el, newHeight) {
// set the height to something new, but remember the original height in case things change
el.data("originalHeight", (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight")));
el.height(newHeight);
}
function getOriginalHeight(el) {
// if the height has changed, send the originalHeight
return (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight"));
}
function columnConform() {
// find the tallest DIV in the row, and set the heights of all of the DIVs to match it.
$('li.half').each(function() {
// "caching"
var $el = $(this);
var topPosition = $el.position().top;
if (currentRowStart != topPosition) {
// we just came to a new row. Set all the heights on the completed row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);
// set the variables for the new row
rowDivs.length = 0; // empty the array
currentRowStart = topPosition;
currentTallest = getOriginalHeight($el);
rowDivs.push($el);
} else {
// another div on the current row. Add it to the list and check if it's taller
rowDivs.push($el);
currentTallest = (currentTallest < getOriginalHeight($el)) ? (getOriginalHeight($el)) : (currentTallest);
}
// do the last row
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);
});
}
$(window).resize(function(){
columnConform();
});
// Dom Ready
// You might also want to wait until window.onload if images are the things that
// are unequalizing the blocks
$(function() {
columnConform();
});
});
如果您能弄清楚如何在调整窗口大小时调整 setConformingHeight,请告诉我。
谢谢!
【问题讨论】:
标签: jquery responsive-design fluid-layout equal-heights