gpt4 book ai didi

jquery - 保持侧边栏与内容相同的高度

转载 作者:行者123 更新时间:2023-11-28 04:41:06 24 4
gpt4 key购买 nike

我正在制作一个典型的 wordpress 主题,基于 twentysixteen .

我试图让 .sidebar div 和 .content-area div 一样长。由于多种原因,纯 CSS 解决方案(例如 flexbox)对我不起作用。

所以...这是我的 jQuery 函数:

    window.sidebarSize = function(){ 
( function( $ ) {
var sidebar = $('.sidebar');
var contentArea = $('.content-area');
var viewportWidth = $(window).width();

//only if sidebar is next to contentarea
if (parseInt(viewportWidth) >= 910){
//if sidebar is longer than the content
if(parseInt(sidebar.outerHeight(true)) > parseInt(contentArea.outerHeight(true))){
sidebar.css('height',''); //reset sidebar height to its minimum
// else, sidebar is shorter than content
} else {
sidebar.css('height',contentArea.outerHeight(true)); //make its height the same

}
}
} )( jQuery );

};

这样调用:

jQuery(function($) {    
//a bunch of event handlers here because I'm not sure which of these work
$(window).on('window.onload window.onresize load resize', function() {
window.sidebarSize();
});

上面的工作,虽然有时会出现问题,并且在我刷新页面之前它不会应用。

但现在我有另一个问题。

有时,内容的大小会动态变化(我正在使用 Collapse-O-matic 插件来折叠图库和常见问题解答),我希望边栏也能随之变化。

我尝试了很多解决方案,但都失败了。目前我正在使用 this script , 但它并不总是有效,正如我所描述的 here .

特别是常见问题解答页面,其中内容高度可以连续多次以多种方式更改,脚本将变得疯狂,侧边栏长度将开始看起来不连贯。

任何关于可以改进这些脚本的建议将不胜感激。我有点 javascript 菜鸟。

最佳答案

前端有动态内容,这意味着某些内容是隐藏的,然后在单击(或其他事件控件)时显示。该动态内容将影响其父容器的高度。

显示动态内容时如何调整容器高度相同?

您将需要监听更改内容的事件。换句话说,当打开该内容的控件被单击时,您想要为该事件添加一个监听器。

为什么?然后,当内容向下扩展并改变高度时,您的高度设置脚本可以重新调整两列的 CSS。

实现

使用 twentysixteen 主题中的 HTML 和 CSS 标记,这是动态内容的示例。这JSFiddle example添加常见问题解答内容揭示器。

这是自动调整内容区域和侧边栏列高度的脚本。

/*!
* This script adjusts the column heights
*/
(function($, window, document){
"use strict";

var $contentArea,
$sidebar;

var init = function() {
$contentArea = $('#primary');
$sidebar = $('#secondary');
$('.faq-question').on("click", setHeights);
setHeights();
}

var setHeights = function() {
clearHeights();
var height = getHeight();

$sidebar.css('height', height);
$contentArea.css('height', height + 40);
}

function clearHeights() {
$sidebar.css('height', '');
$contentArea.css('height', '');
}

function getHeight() {
var contentHeight = $contentArea.outerHeight(true),
sidebarHeight = $sidebar.outerHeight(true);

return contentHeight > sidebarHeight
? contentHeight
: sidebarHeight;
}

$(document).ready(function(){
init();
});

}(jQuery, window, document));

当您点击问题时,答案就会显示出来。这样做时,内容容器的高度会发生变化。该脚本正在监听该点击事件。单击时,它会重新触发 setHeights() 函数。

如何添加点击监听?

对于您正在使用的插件,您需要查看它打开和关闭内容的目标。然后您可以添加自己的事件以重新触发设置高度。

关于jquery - 保持侧边栏与内容相同的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201814/

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