我使用以下函数来分析两列(内容和边栏)并确保 div 的高度相等。此功能仅在列需要增加大小时才有效。因此,当内容大小减小时,它会使列太大。
如何更改此代码以解决内容尺寸减小的问题(例如,如果窗口尺寸从中等宽度变为较大宽度,并且最高内容高度将减小。)
var sidebarSameHeight = function() {
//Sidebar Same Height - http://html-tuts.com/make-sidebar-same-height-as-content-div/
// placing objects inside variables
var content = $('.core_content_main');
var sidebar = $('.core_content_sidebar');
// get content and sidebar height in variables
var getContentHeight = content.outerHeight();
var getSidebarHeight = sidebar.outerHeight();
// check if content height is bigger than sidebar
if ( getContentHeight > getSidebarHeight ) {
sidebar.css('min-height', getContentHeight);
}
// check if sidebar height is bigger than content
if ( getSidebarHeight > getContentHeight ) {
content.css('min-height', getSidebarHeight);
}
};
sidebarSameHeight();
setInterval(sidebarSameHeight, 250);
最佳答案
当前代码仅检查一列是否高于另一列。您需要重复并反转逻辑以检查一个是否小于另一个。我们不能每次都运行两个测试(更大或更小),所以如果我们记录以前的高度,我们可以检查它并决定我们需要做什么。
var sidebarSameHeight = function () {
// placing objects inside variables
var content = $('.core_content_main');
var sidebar = $('.core_content_sidebar');
// get content and sidebar height in variables
var getContentHeight = content.outerHeight();
var getSidebarHeight = sidebar.outerHeight();
//get the previous height
var contentOldHeight = content.data("oldHeight");
var sidebarOldHeight = sidebar.data("oldHeight");
//Check if either has reduced - if true use reduce logic for columns
if (contentOldHeight > getContentHeight || sidebarOldHeight > getSidebarHeight) {
// check if content height is smaller than sidebar
if (getContentHeight < getSidebarHeight) {
sidebar.css('min-height', getContentHeight);
}
// check if sidebar height is smaller than content
if (getSidebarHeight < getContentHeight) {
content.css('min-height', getSidebarHeight);
}
} else {
// check if content height is bigger than sidebar
if (getContentHeight > getSidebarHeight) {
sidebar.css('min-height', getContentHeight);
}
// check if sidebar height is bigger than content
if (getSidebarHeight > getContentHeight) {
content.css('min-height', getSidebarHeight);
}
}
//Set data values for next time
content.data("oldHeight", getContentHeight);
sidebar.data("oldHeight", getSidebarHeight);
};
sidebarSameHeight();
setInterval(sidebarSameHeight, 1000);
这jsfiddle example 允许您在彩色框中键入内容并查看框一起展开和折叠。我将延迟增加到一秒以使其更加明显。
这可能不是适合您的完整解决方案,但应该能让您顺利上路。
关于jquery - 使列等高(上下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331442/