jquery - 使用 jQuery 使侧边栏与内容高度相同
问题描述
我的jQuery代码如下。当我 SHIFT 刷新时,侧边栏似乎是全高,但有时在加载页面时,侧边栏下方有空白区域,并且不是全高。难道我做错了什么?
jQuery(document).ready(function(){
var contentheight = jQuery('.storycontent').outerHeight(true);
jQuery('.page #sidebar').height( contentheight );
jQuery('.page-template-inside-page #sidebar').css("height",
contentheight);
jQuery('.page-template-inside-page .storycontent').css("height",
contentheight);
});
jQuery(window).resize(function(){
var contentheight = jQuery('.storycontent').outerHeight(true);
jQuery('.page #sidebar').height( contentheight );
jQuery('.page-template-inside-page #sidebar').css("height",
contentheight);*
jQuery('.page-template-inside-page .storycontent').css("height",
contentheight);
});
解决方案
如果您缩减代码并遵循 DRY(D on't R epeat Y ourself )原则,通常更容易调试。
由于#sidebar 是一个ID,它应该只在页面中出现一次,因此
.page #sidebar'
并.page-template-inside-page #sidebar
引用同一个元素,如果您有两个不同的元素,ID 为#sidebar,这可能是您的问题的一部分,请考虑改用一个类。
如果您以更紧凑的方式编写代码,则可以这样编写。
jQuery(()=>{
function setHeight(){
jQuery(".page-template-inside-page").find(".storycontent, #sidebar").css({
height: jQuery('.storycontent, #sidebar').outerHeight(true)
});
};
jQuery(window).resize(setHeight);
setHeight();
});
以这种方式编写时,您可以看到您将外部高度设置为高度,这不是相同的值。outterHeight 包括边距和填充,高度不包括。它也没有考虑到侧边栏可能更长
代码可以像这样更健壮地编写。
jQuery(()=>{
function setHeight(){
//use Math.max to get the height of the taller element
const height = Math.max(
jQuery("#sidebar").height(),
jQuery(".page-template-inside-page .storycontent").height()
);
//if you need to select more then one element, you can separate them with commas
jQuery("#sidebar, .page-template-inside-page .storycontent").css({
height: height
});
};
jQuery(window).resize(setHeight); //call the setHeight function on resize
setHeight(); //call the setHeight function when the document loads.
});
我没有您的 html 标记或 css,如果元素是嵌套的(一个在另一个内部),请确保内部元素没有顶部或底部填充。
PS。问题是关于如何用 jQuery 来做......但用纯 css 来做会更容易/更快...... https://davidwalsh.name/flexbox-column