您的位置:首页 > 其它

使用 position: sticky 达到粘性元素区域悬浮效果

2016-07-14 12:09 579 查看
在一些很长的表格中,常常会使用表头悬浮的设计以方便阅读,即在表格离开窗口之前,表头会一直 fixed 悬浮在表格的最顶上。还有许多诸如评论框等元素,也采用了这种被称为 Sticky Pin 或者 粘性元素 的设计。

 

这种效果一直以来需要通过 JavaScript 实现。不过就在去年,这项结合了 Relative (在屏幕中时) 和 Fixed (移出屏幕时) 的样式效果被提案添加到了 CSS3 中。下面是一个示例:

Html代码  


.sticky {  

    position: -webkit-sticky;  

    position: -moz-sticky;  

    position: -ms-sticky;  

    position: sticky;  

    top: 15px; // 使用和 Fixed 同样的方式设定位置  

}  

 

因为这个样式尚未进入标准,还必须使用私有前缀。这里介绍一下浏览器兼容更好的 JS 实现方式:

 

一个不错的选择是使用 jQuery Pin 这个方便的 jQuery 脚本,支持简单的 Pin 元素、在容器范围内 Pin (例如 Table 内 Pin 住 Th)、在一定尺寸下禁用的功能。

 

如果要使用原生 JS 实现,可以参照下面的代码:

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>  

 

 完整代码:

Html代码  


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

长按图片识别图中二维码(或搜索微信公众号FrontEndStory)关注“前端那些事儿”,带你探索前端的奥秘。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: