position:sticky
是一个新的css3属性,它的表现类似position:relative
和position:fixed
的合体,在目标区域在屏幕中可见时,它的行为就像position:relative;而当页面滚动超出目标区域时,它的表现就像position:fixed,它会固定在目标位置。
HTML5浏览器实现:
<!-- lang: css -->
.sticky {
position: -webkit-sticky;
position:sticky;
top: 15px;
}
其他浏览器实现:
<!-- lang: html -->
<style>
.sticky { position: fixed; top: 0; }
.header { width: 100%; background: #F6D565; padding: 25px 0; }
</style>
<div class="header"></div>
<script>
var header = document.querySelector('.header');
var origOffsetY = header.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY ? header.classList.add('sticky') : header.classList.remove('sticky');
}
document.addEventListener('scroll', onScroll);
</script>