position:sticky定义, eg:CSS中position属性介绍(新增sticky)
设置了sticky的元素,在屏幕范围(viewport)时该元素的位置并不受到定位影响(设置是top、left等属性无效),当该元素的位置将要移出偏移范围时,定位又会变成fixed,根据设置的left、top等属性成固定位置的效果。
sticky属性有以下几个特点:
看了效果我就会很清楚的知道他的作用,在实际应用中,eg:导航栏随屏幕滚动定位顶部,侧边栏广告随滚动定位顶部等。
以导航栏随屏幕滚动定位顶部为实例:
优点:
缺点:
.module-nav{
color: #ffea00;
width: 7rem;
font-size: 0.28rem;
height: 0.65rem;
line-height: 0.6rem;
display: table;
table-layout: fixed;
padding: 0 0.25rem;
text-align: center;
background: #fbbd09;
}
.module-nav.nav1{
position: fixed;
top: 0;
left: 0;
z-index: 10000;
display:none;
}
.module-nav span{
display: table-cell;
background: url(./images/nav-bg.jpg) no-repeat right center/1.7rem 0.65rem;
}
.module-nav span.active{color: #fff;}
<nav class="module-nav">
<span class="active">生态餐桌</span>
<span>茗茶名酒</span>
<span>美食物语</span>
<span>居家生活</span>
</nav>
<nav class="module-nav nav1">
<span class="active">生态餐桌</span>
<span>茗茶名酒</span>
<span>美食物语</span>
<span>居家生活</span>
</nav>
$(window).scroll(function(){
var bodyTop = $('html,body').scrollTop();
var goodTop = $('.goods').offset().top;
bodyTop >= goodTop ? $('.nav1').show() : $('.nav1').hide();
});
注意:在移动端如果导航要居中显示,要对nav1的left进行计算赋值。
通过对导航的position的值在fixed和relative切换,来实现
优点:
缺点:
.module-nav{
position: relative;
top: 0;
left: 0;
z-index: 10000;
color: #ffea00;
width: 7rem;
font-size: 0.28rem;
height: 0.65rem;
line-height: 0.6rem;
display: table;
table-layout: fixed;
padding: 0 0.25rem;
text-align: center;
background: #fbbd09;
}
.module-nav span{
display: table-cell;
background: url(./images/nav-bg.jpg) no-repeat right center/1.7rem 0.65rem;
}
.module-nav span.active{color: #fff;}
<nav class="module-nav">
<span class="active">生态餐桌</span>
<span>茗茶名酒</span>
<span>美食物语</span>
<span>居家生活</span>
</nav>
$(window).scroll(function(){
var bodyTop = $('html,body').scrollTop();
var goodTop = $('.goods').offset().top;
bodyTop >= goodTop ? $('.module-nav').css('position','fixed') : $('.module-nav').css('position','');
});
注意:在fixed定位的时候需要进行left的计算,否则会导致导航的不居中。
直接对导航使用position:sticky,就能实现上边看着复杂的效果。
优点:
缺点:
.module-nav{
position: sticky;
top: 0;
left: 0;
z-index: 10000;
color: #ffea00;
width: 7rem;
font-size: 0.28rem;
height: 0.65rem;
line-height: 0.6rem;
display: table;
table-layout: fixed;
padding: 0 0.25rem;
text-align: center;
background: #fbbd09;
}
.module-nav span{
display: table-cell;
background: url(./images/nav-bg.jpg) no-repeat right center/1.7rem 0.65rem;
}
.module-nav span.active{color: #fff;}
<nav class="module-nav">
<span class="active">生态餐桌</span>
<span>茗茶名酒</span>
<span>美食物语</span>
<span>居家生活</span>
</nav>
注意:由于兼容性问题,所以sticky可以在移动端使用,代码简单,容易理解。但是要注意所选择的容器!