<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js 滚动导航实现定位</title>
<style>
body {
margin: 0;
text-align: center;
font-family: sans-serif;
}
.fixed {
position: fixed;
top: 0;
}
.sticky {
width: 100%;
background: #F6D565;
padding: 25px 0;
text-transform: uppercase;
}
</style>
</head>
<body>
<p style="margin-bottom:100px;">滚动此页面。</p>
<div class="sticky"><h3>头部</h3></div>
<p style="margin-top:500px;">内容1</p>
<p style="margin-top:500px;">内容2</p>
<p style="margin-top:500px;">底部</p>
<script>
var sticky = document.querySelector('.sticky');
var origOffsetY = sticky.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY ? sticky.classList.add('fixed') : sticky.classList.remove('fixed');
}
document.addEventListener('scroll', onScroll);
</script>
</body>
</html>
网友评论