偶然得知了position:sticky这个新属性,想起了从前写这个功能时的蛋疼时光。。。一堆高度算来算去,比来比去,emmm。。。
position:sticky;基于用户的滚动位置来定位。
粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。
在目标区域以内,它的行为就像 position:relative; 而当页面滚动超出目标区域时,它的表现就像 position:fixed;,它会固定在目标位置。
元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。
这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
下附demo
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定位的新属性position:sticky;</title>
<style type="text/css">
.top {
height: 500px;
background: yellowgreen;
}
.pos {
height: 100px;
background: blue;
position: -webkit-sticky;
position: sticky;
top: 0;
/*阈值*/
}
.pos22 {
height: 100px;
background: yellow;
position: -webkit-sticky;
position: sticky;
top: 100px;
/*阈值*/
}
.bottom1 {
height: 500px;
background: grey;
}
.bottom {
height: 1600px;
background: grey;
}
</style>
</head>
<body>
<div class="top">上边元素</div>
<div class="pos">定位元素</div>
<div class="bottom1">底部元素</div>
<div class="pos22">定位元素222</div>
<div class="bottom">底部元素</div>
<script src="../lib/jquery-1.8.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$('.pos22').click(function() {
window.scrollTo(0, 1500)
})
</script>
</body>
</html>
本文深入探讨CSS中position:sticky属性的应用,通过实例演示如何利用该属性实现元素的粘性定位,即元素在滚动到特定阈值前为相对定位,之后转为固定定位,提供了一种更优雅的布局解决方案。
509

被折叠的 条评论
为什么被折叠?



