Javascript 如何消除人为固定元素滚动时的闪烁?

Javascript 如何消除人为固定元素滚动时的闪烁?,javascript,css,Javascript,Css,这是一个将一个元素粘贴到另一个元素可见区域顶部的非常简单的示例。滚动.container时,.fixed保持在顶部 <div class="container"> <div class="fixed">fixed content</div> <div class="content">regular content<br/>regular content<br/>regular content<br/&g

这是一个将一个元素粘贴到另一个元素可见区域顶部的非常简单的示例。滚动
.container
时,
.fixed
保持在顶部

<div class="container">
    <div class="fixed">fixed content</div>
    <div class="content">regular content<br/>regular content<br/>regular content<br/>regular content<br/>regular content</div>
</div>

<style type="text/css">
.container {
    position: relative;
    border: 1px solid blue;
    overflow: auto;
    width: 250px;
    height: 250px;
}
.content {
    height: 500px;
    width: 500px;
}
.fixed {
    position: absolute;
    width: 500px;
    margin-top: 2rem;
    border 1px solid red;
}
</style>

<script type="text/javascript">
    $('.container').scroll(function () {
        var top = $('.container').prop('scrollTop');
        console.log(top);
        $('.fixed').css('top', top);
    });
</script>

固定内容
常规内容
常规内容
常规内容
常规内容
常规内容
.集装箱{ 位置:相对位置; 边框:1px纯蓝色; 溢出:自动; 宽度:250px; 高度:250px; } .内容{ 高度:500px; 宽度:500px; } .固定{ 位置:绝对位置; 宽度:500px; 边缘顶端:2rem; 边框1px纯红; } $('.container')。滚动(函数(){ var top=$('.container').prop('scrollTop'); 控制台日志(顶部); $('.fixed').css('top',top); });
问题是如果浏览器速度不够快,
.fixed
元素在我滚动时闪烁。它滞后于滚动(滚动时将
.fixed
中文本的位置与
.content
中的文本进行比较)。在我的桌面上,它工作得完美无缺,但当我尝试在虚拟机上用Chromium运行它时,我可以看到闪烁

在浏览器呈现页面之前,是否有其他方法捕获滚动事件并设置my
.fixed
元素的位置


编辑更新示例以包括水平滚动。固定元件只能垂直固定。

使用双容器:

<div class="container-wrapper">
    <div class="fixed">fixed content</div>
    <div class="container">
        <div class="content">regular content<br/>regular content<br/>regular content<br/>regular content<br/>regular content</div>
    </div>
</div>
这样,滚动时就不需要jQuery来重新定位
.fixed
div,而且它也不会闪烁

编辑以解决水平滚动

$('.container').on('scroll', function() {
    var left = this.scrollLeft;
    $('.fixed').css('left', -left + 'px');
});

这将移动
.fixed
div而不闪烁。在您的解决方案中,之所以会出现闪烁,是因为浏览器在滚动时移动了div,然后事件处理程序再次移动它。现在它只移动一次。

这是实际页面的一部分。由于页面的实际布局(要复杂得多),我无法使用
position:fixed
。这是我能做的复制行为的最小代码。我的示例不完整。我有水平滚动,我需要的固定内容实际上是垂直固定的(如我的例子),并垂直滚动。现在我将更新它。编辑我的解决方案,使其包含一点jQuery,以便在水平滚动时移动对象
$('.container').on('scroll', function() {
    var left = this.scrollLeft;
    $('.fixed').css('left', -left + 'px');
});