sticky属性

忘记说了,position 还有一个 「sticky」 属性值,不是「static」哦!该属性值类似 relative 和 fixed 的合体,当元素在视口内的时候表现类似relative,当滚动后元素移出视口就会固定在那里,类似fixed。目前Chrome 23.0.1247.0 开始支持,W3C讨论:http://t.cn/zTrkHq2,Demo:http://t.cn/zWeNSjJ

在微薄上看到这条微薄和一些讨论 @一丝yisi

研究了下源码,发觉利用fixed和js简单实现

贴上主要代码:

<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>

<p style="margin-bottom:100px;">Scroll this page.</p>
<div class="sticky"><h3>Super amazing header</h3></div>
<p style="margin-top:500px;">Still there?</p>
<p style="margin-top:500px;">Yep!</p>
<p style="margin-top:500px;">Scroll so hard!</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>
View Code

 

 
posted @ 2013-05-14 15:26  GM_Lv  阅读(296)  评论(0编辑  收藏  举报