主要使用display: flex; + overflow: hidden; 实现
思路:列表和列表底部的dom为相邻元素,给它们共同的父元素添加一个高度、弹性盒属性和超出隐藏;给列表添加超出隐藏显示滚动条属性;给底部dom的子元素添加一个高度
视频演示:
HTML:列表底部dom跟随列表的内容增加而移动并触底固定
效果图:
主要HTML代码:
<div class="list-box">
<div class="list">
<!-- <div class="list-item"></div> -->
</div>
<div class="foolter-box">
<div class="foolter">
</div>
</div>
</div>
主要CSS代码:
.list-box {
width: 100%;
height: 400px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.list {
overflow-y: auto;
}
.list-item {
width: 100%;
height: 100px;
background-color: aqua;
margin-bottom: 10px;
}
.foolter {
width: 100%;
height: 30px;
background-color: blue;
}
HTML文件全部代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: fixed;
top: 100px;
left: 50%;
transform: translate(-50%);
width: 400px;
height: 500px;
border: 1px solid rgb(64, 56, 56);
border-radius: 2px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.header {
width: 100%;
flex: 1;
border-bottom: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
background-color: red;
}
#btn {
width: 200px;
height: 80px;
background-color: orange;
}
.list-box {
width: 100%;
height: 400px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.list {
overflow-y: auto;
}
.list-item {
width: 100%;
height: 100px;
background-color: aqua;
margin-bottom: 10px;
}
.foolter {
width: 100%;
height: 30px;
background-color: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="header">
<button id="btn">添加一个item</button>
</div>
<div class="list-box">
<div class="list">
<!-- <div class="list-item"></div> -->
</div>
<div class="foolter-box">
<div class="foolter">
</div>
</div>
</div>
</div>
<script>
let listArr = [
{
id: 0,
text: '删除当前item'
}
]
const btn = document.getElementById('btn')
let list = document.querySelector('.list')
let foolter = document.querySelector('.foolter')
function newListArrFn(listArr) {//列表和底部dom内容
list.innerHTML = listArr.reduce((returnValue, item) => {//列表内容
return returnValue ? returnValue + `<div class='list-item' id=${item.id}>${item.id}--${item.text}</div>` :
`<div class='list-item' id=${item.id}>${item.id}--${item.text}</div>`
}, null)
foolter.innerHTML = `列表长度为:${listArr.length}`//底部内容
}
newListArrFn(listArr)//初次展示
btn.addEventListener('click', () => {//添加一项item
listArr.push({
id: new Date().getTime(),
text: '删除当前item'
})
newListArrFn(listArr)
})
list.addEventListener('click', function (e) {//删除一项item
listArr = listArr.filter(_ => _.id != e.target.id)
newListArrFn(listArr)
})
</script>
</body>
</html>