顶部固定,左侧滚动,右侧滚动,彼此独立
实现一个网页功能。
顶部区域,左右布局。
顶部的内容固定不变(始终在最顶部),左侧内容超出滚动,右侧内容超过滚动,左右2侧的滚动互不影响
实现滚动的2个条件:
1,滚动的容器需要设置固定的高度
2,设置overflow-y: auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
.top-cont{
height: 100px;
background-color: aqua;
}
.cont-box{
display: flex;
}
.left-box{
scrollbar-width:none;
overflow-y: auto;
width: 300px;
background-color: antiquewhite;
}
.right-box{
flex: 1;
overflow-y: auto;
background-color: aquamarine;
}
.item-box{
height: 400px;
background-color: #fff;
margin-bottom: 10px;
}
.item-box2{
height: 400px;
background-color: pink;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="top-cont" id="topCont">
顶部区域
</div>
<div class="cont-box">
<div class="left-box" id="leftBox">
<div class="item-box">AAA1</div>
<div class="item-box">AAA2</div>
<div class="item-box">AAA3</div>
<div class="item-box">AAA4</div>
<div class="item-box">AAA5</div>
<div class="item-box">AAA6</div>
</div>
<div class="right-box" id="rightBox">
<div class="item-box2">AAA1</div>
<div class="item-box2">AAA2</div>
<div class="item-box2">AAA3</div>
<div class="item-box2">AAA4</div>
<div class="item-box2">AAA5</div>
<div class="item-box2">AAA6</div>
</div>
</div>
<script></script>
</body>
<script>
// 动态获取顶部区域的高度
const topCont = document.getElementById('topCont')
const topContNodeHeight = topCont.offsetHeight
console.log('获取顶部元素的高度', topContNodeHeight)
// 设置左侧的区域,设置固定高度
const leftBox = document.getElementById('leftBox')
leftBox.style.height = `calc(100vh - ${topContNodeHeight }px)`
// 设置右侧的区域,设置固定高度
const rightBox = document.getElementById('rightBox')
rightBox.style.height = `calc(100vh - ${topContNodeHeight }px)`
</script>
</html>
为啥顶部没有设置固定定位
顶部区域固定位置,确实可以设置固定定位,也是实现的一种办法。
还有一种办法就是:让这个页面的高度始终不超过body的高度(文中就是使用的这种办法)
页面如何不产生滚动条
子元素的高度不超出了父元素的高度,就不会产生滚动条。
也就是说:如果页面产生滚动条,就说明子元素的高度超出了父元素的高度了。
如何隐藏左侧的滚动条
.left-box{
// 隐藏左侧的滚动条
scrollbar-width:none;
overflow-y: auto;
width: 300px;
}
offsetHeight
offsetHeight 返回元素的高度(整数,四舍五入),它包含以下部分:
offsetHeight = content + padding + border + 水平滚动条(如果有就会包含)
也就是是不包含margin哈。在说一次,不包含margin。