DOM:滚动时固定导航栏
简单实现滚动时固定导航栏
实例代码:
<!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>
</head>
<style>
body {
margin: 0;
}
.div1 {
background-color: aqua;
width: 200px;
height: 200px;
font-size: 30px;
}
.div2 {
background-color: darkcyan;
width: 200px;
height: 200px;
font-size: 30px;
}
.div3 {
background-color: darkgreen;
width: 200px;
height: 2000px;
font-size: 30px;
}
</style>
<body>
<div class='div1'>aqua</div>
<div class='div2'>darkcyan</div>
<div class='div3'>darkgreen</div>
<script>
window.onload = function () {
document.body.onscroll = function () {
let pY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop
var div2 = document.querySelector('.div2')
var div3 = document.querySelector('.div3')
if (pY > 200) {
div2.style.position = 'fixed'
div2.style.top = '0px'
div3.style.lineHeight= '2000px';
} else {
div2.style.position = ''
div2.style.top = ''
}
}
}
</script>
</body>
</html>
效果图:
滑动前:

滑动后:

浙公网安备 33010602011771号