20行js = 2行css, css yyds!!!
以下两篇搞懂原理
彻底理解粘性定位 - position: sticky - 简书
搞清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop_飞歌Fly的博客-优快云博客_offsetheight
0.需求,使大红色框在滚动到顶部后,固定到顶部
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
width: 100%;
height: 100px;
margin-bottom: 15px;
background-color: pink;
}
#red {
background-color: red;
}
body {
height: 3000px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="red"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
1.使用css
直接给#red添加属性position:sticky; top:0;
#red {
background-color: red;
position:sticky;
top:0;
}
2.使用js
css 不变,依旧是 0.需求中的样式,添加js
<script>
//逻辑
var oDiv = document.getElementById("red");
//div在页面的占位高,div到body的距离
var otop = oDiv.offsetTop;
console.log('otop', otop)
//页面滚动
window.onscroll = function () {
//获取页面的滚动距离
var oheight = document.documentElement.scrollTop || document.body.scrollTop;
console.log('oheight', oheight)
//滚动到一定位置 div固定到顶部 js实现吸顶
if (otop < oheight) {
oDiv.style.position = "fixed";
oDiv.style.top = 0;
} else {
oDiv.style.position = "relative";
}
}
</script>