吸顶方法:
// 吸顶
const scroll = function () {
if (document.body.scrollTop >= 300 || document.documentElement.scrollTop >= 300) {
document.querySelector(.nav).style.position = fixed
document.querySelector(.nav).style.top = 0
} else if (document.body.scrollTop <= 300 || document.documentElement.scrollTop <= 300) {
document.querySelector(.nav).style.position = relative
document.querySelector(.nav).style.top = 300px
}
}
调用:
window.onscroll = document.body.onscroll = scroll
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
width: 100%;
min-height: 200vh;
position: relative;
padding: 0;
margin: 0;
}
.nav {
/* position: fixed; */
position: relative;
top: 300px;
width: 100%;
height: 50px;
background-color: rgb(40, 128, 101);
}
</style>
<body>
<div class="nav"></div>
</body>
<script>
// 吸顶
const scroll = function () {
if (document.body.scrollTop >= 300 || document.documentElement.scrollTop >= 300) {
document.querySelector(.nav).style.position = fixed
document.querySelector(.nav).style.top = 0
} else if (document.body.scrollTop <= 300 || document.documentElement.scrollTop <= 300) {
document.querySelector(.nav).style.position = relative
document.querySelector(.nav).style.top = 300px
}
}
// document.body.addEventListener(scroll, scroll, false)
window.onscroll = document.body.onscroll = scroll
</script>
</html>