固定定位
页面上实现滚动时触发固定定位
<style>
* {
margin: 0;
padding: 0;
}
.progressbar {
height: 3px;
background: skyblue;
position: fixed;
top: 0;
left: 0;
width: 30%;
}
</style>
</head>
<body>
<div class="progressbar"></div>
<div style="height: 500px;"></div>
<div class="demo" style="height:100px;background:#000;top:0;width:100%"></div>
<div style="height:2000px">
</div>
<script>
let demo = document.querySelector('.demo')
let offsetTop = demo.offsetTop
window.onscroll = () => {
let scrollTop = Math.floor(document.documentElement.scrollTop)
let maxScrollTop = document.body.offsetHeight - window.innerHeight
let percent = (scrollTop * 100 / maxScrollTop) + '%'
document.querySelector('.progressbar').style.width = percent
if (scrollTop > offsetTop) {
demo.style.position = 'fixed'
} else {
demo.style.position = 'static'
}
}
</script>
</body>