position:sticky介绍
position:sticky介绍 用户的屏幕越来越大,而页面太宽的话会不宜阅读,所以绝大部分网站的主体宽度和之前相比没有太大的变化,于是浏览器中就有越来越多的空白区域,所以你可能注意到很多网站开始在滚动的时候让一部分内容保持可见,比如,侧边栏的部分区域。position:sticky为此而生。 position:sticky用法 position:sticky是一个新的css3属性,它的表现类似position:relative和position:fixed的合体,在目标区域在屏幕中可见时,它的行为就像position:relative; 而当页面滚动超出目标区域时,它的表现就像position:fixed,它会固定在目标位置。 使用起来也非常简单: .sticky { position: -webkit-sticky; position:sticky; top: 15px; } 目前来说还需要用私有前缀~~ sticky生效条件: 1、父元素不能overflow:hidden或者overflow:auto属性。(mescroll-body设置:sticky="true"即可, mescroll-uni本身没有设置overflow) 2、必须指定top、bottom、left、right4个值之一,否则只会处于相对定位 3、父元素的高度不能低于sticky元素的高度 4、sticky元素仅在其父元素内生效,所以父元素必须是 mescroll 浏览器兼容性: 由于这是一个全新的属性,以至于到现在都没有一个规范,W3C也刚刚开始讨论它,而现在只有webkit nightly版本和chrome 开发版(Chrome 23.0.1247.0+ Canary)才开始支持它。 另外需要注意的是,如果同时定义了left和right值,那么left生效,right会无效,同样,同时定义了top和bottom,top赢~~ fall back 虽然其它浏览器尚不支持,但是实现起来其实不难,我们可以用js简单实现: HTML CSS .sticky { position: fixed; top: 0; } .header { width: 100%; background: #f6d565; padding: 25px 0; } JS 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); 这里是一个简单的demo。 嗯,对于前端来说,新技术用于提升用户体验才能体现其价值~~ 本文转载,原文来源于:https://www.qianduan.net/position-sticky-introduction/
position:sticky介绍



嗯,对于前端来说,新技术用于提升用户体验才能体现其价值~~
本文转载,原文来源于:https://www.qianduan.net/position-sticky-introduction/