在OSX Safari(适用于Chrome/Firefox)上,滚动事件期间的CSS定位无响应和抖动

CSS positioning during scroll event unresponsive and jittery on OSX Safari (works in Chrome/Firefox)

本文关键字:事件 CSS 定位 抖动 响应 滚动 适用于 Safari OSX Chrome Firefox      更新时间:2023-09-26

我在我的网站上有一个粘性边框,在窗口的滚动事件期间,我更新它,当用户滚动时跟随窗口。

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上也能顺利更新吗?

(position:fixed不是一个选项,因为它需要响应不固定的兄弟CSS过渡)

使用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)'
    });
});