position:sticky是一个新的css3属性,它的表现类似position:relative和position:fixed 的合体,当目标区域在屏幕中可见时,它的行为就像position:relative;当页面滚动超出目标区域时,它的表现就像position:fixed,它会固定在目标位置。(注意:top和left优先级分别大于bottom和right)
原生实现:
<style> .header { width: 100%; background: #f6d565; padding: 25px 0; } .sticky { position: fixed; top: 0; } </style> <body> <div style='height: 200px;'></div> <div class="header"></div> <div style='height: 1000px;'></div> </body> <script> var header = document.querySelector('.header'); var originOffsetY = header.offsetTop;//获取该元素初始的距父元素顶部的高度 function onScroll(e) { window.scrollY >= originOffsetY///屏幕顶部到页面顶部的距离大于获取的原始值 ? header.classList.add('sticky') : header.classList.remove('sticky') } document.addEventListener('scroll', onScroll) </script>