jquery - 通过 CSS 根据另一个 div 调整 div 的高度
问题描述
我有两个 DIV(一个是侧边栏,另一个是内容部分),我需要具有相同的高度,但我有一个问题。侧边栏包括一些li
s。我希望侧边栏的高度与内容部分相同,但是当我使用 时flex
,侧边栏的高度可以比内容部分长(因为两个部分都是动态的)。所以当高度长于内容部分时,我需要滚动侧边栏。
<section class="container">
<div class="sidebar">
<ul>
<li><li>
<li><li>
<li><li>
<li><li>
<li><li>
</ul>
</div>
<div class="content"></div>
</section>
我的 CSS 代码:
.container {
display: flex;
}
.sidebar,.content {
flex: 1 0 auto;
}
我什至使用了 JQuery,但我们看到了错误的高度,因为图像在内容部分加载缓慢。
我的 jQuery 代码:
jQuery(document).ready(function($) {
$(".sidebar").height($(".content").height());
});
我什至使用了以下代码,但没有任何反应:
jQuery( window ).load(function($) {
$(".sidebar").height($(".content").height());
});
我不想使用position:absolute
,因为...您可以在此链接中看到我的页面:https ://end-eng.com/landing-grammar/
解决方案
你所拥有的非常接近!如果您改为在父级上设置 flex 属性,您将拥有两个等高的 div。我添加了一些颜色来说明:
.container {
display: flex;
flex: 1 0 auto;
}
.sidebar {
background: red;
}
.content {
background: lime;
}
<section class="container">
<div class="sidebar">
<ul>
<li><li>
<li><li>
<li><li>
<li><li>
<li><li>
</ul>
</div>
<div class="content">hello content</div>
</section>
flex
以下是您正在使用的速记的一些读物: https ://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow
如果您需要在高度长于内容时滚动侧边栏,那么您可以使用 jQuery 来匹配resize
事件中元素的高度(以保持一致),如下所示:
$(document).ready(function() {
var a = '.content';
var b = '.sidebar'
matchHeight(a, b); // set at beginning
$(window).resize(function() {
matchHeight(a, b); // reset on window resize
})
});
// set height of one element to another
// target: height to match
// el: element to match to target height
function matchHeight(target, el) {
var targetHeight = $(target).height();
$(el).css('height', targetHeight);
}
.container {
display: flex;
flex: 1 0 auto;
}
.sidebar {
background: red;
overflow-y: scroll;
min-width: 50px;
}
.sub-container {
background: lime;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="container">
<div class="sidebar">
<ul>
<li>
<li>
<li>
<li>
<li>
<li>
<li>
<li>
<li>
<li>
</ul>
</div>
<div class="sub-container">
<div class="content">
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source.
</div>
</div>
</section>
推荐阅读
- javascript - 试图抓取,但我无法通过“通知”启动页面 - “单击”带有 python 请求的 JS 按钮
- angular - 如何将两个不同的状态从我的 ngrx 效果传递到我的服务功能?
- activecollab - ActiveCollab:命令行 curl 外部登录不返回任何内容
- azure - Azure,“传入客户端证书”选项去了哪里?
- javascript - invalid_json 的 chat.postMessage 响应
- reactjs - 将 React Typescript 应用程序转换为 Nextjs
- r - 可以使用 csv 文件在 url 中下载多个 zip 文件吗?
- mlp - 使用求解器 sgd 时出现 MLPRegressor 错误
- listview - 在 ListView 中滚动数据
- python-3.x - 我需要使用 dict 方法找到 5 个最常用的单词以及 moodle 系统提供的单词