position:sticky粘性定位

项目中可能会遇到这样的需求:当页面某个元素滚动到顶部时,让其定位或悬浮在顶部,以下图红框区域所示:
在这里插入图片描述
在这里插入图片描述
实现以上效果的最简单方式,是使用C3提供的新属性position:sticky。而后设置top值等于顶部导航的高度便可。同理,根据效果能够设置 right,bottom,left。web

MDN给出的说明:svg

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.rest

使用 top,right,bottom,left 设置定位值,滚动未超过定位值时,元素不受定位影响(即 top,right,bottom,left等设置无效)
当元素的位置将要滚动偏移越过定位值时,元素定位会变成fixed,根据设置的 top,right,bottom,left 属性定位。
设置为 sticky 的元素并未脱离文档流,不会影响相邻其余元素的正常显示orm

因为是新增属性,兼容性并很差:
在这里插入图片描述
因此实际开发,若是要实现这个效果,能够监听滚动事件,来动态改变定位样式,是否使用 fixed;也能够使用多个一样的元素,放在不一样位置,动态切换显示与隐藏,保证同一时间只会显示一个在页面上。xml