(position:fixed不是一个选项,因为它需要响应不固定的兄弟CSS过渡)
我在我的网站上有一个粘性边框,在窗口的滚动事件期间,我更新它,当用户滚动时跟随窗口。
CSS:.fixed {
position: relative;
background: black;
color: white;
height: 40px;
}
.container {
height: 2000px;
}
HTML: <div class="container">
<div class="fixed">Fixed</div>
</div>
JS:
$(window).scroll( function() {
$('.fixed').css({top: $(window).scrollTop()});
});
演示:https://jsfiddle.net/xt8c00yq/
我知道滚动事件在移动浏览器上不可靠且无响应,所以我已经在设备上禁用了它。然而,在Safari的桌面版上,它似乎也很慢而且不稳定。它在Chrome和Firefox上都运行良好。在这两个浏览器上测试演示,你自己看看。
有什么已知的技巧可以使它在Safari上也能顺利更新吗?
使用translate3d
实现硬件加速渲染
$(window).scroll( function() {
scrolled = $(window).scrollTop();
$('.fixed').css({
'-webkit-transform' : 'translate3d(0,' + scrolled + 'px,0)',
'-moz-transform' : 'translate3d(0,' + scrolled + 'px,0)',
'-ms-transform' : 'translate3d(0,' + scrolled + 'px,0)',
'-o-transform' : 'translate3d(0,' + scrolled + 'px,0)',
'transform' : 'translate3d(0,' + scrolled + 'px,0)'
});
});