我的网站有视差效果,但在滚动时它看起来相当跳跃,如下所示:
代码如下:
jQuery(document).ready(function() {
jQuery(window).scroll(function() {
jQuery('*[class^="prlx"]').each(function(r) {
var pos = $(this).offset().top;
var scrolled = $(window).scrollTop();
jQuery('*[class^="prlx"]').css('top', +(scrolled * 0.6) + 'px');
});
});
});
*[class^="prlx"] {
position: absolute;
width: 100%;
height: 300%;
top: 0;
left: 0;
z-index: -1;
background-size: 110%;
}
.prlx-2 {
background-image: url('http://www.roscodigitalmedia.co.uk/rosco/wp-content/uploads/2015/12/bigstock-Artist-Photographer-Retouches-91840682.jpg');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container-fluid homeHeader">
<div class="prlx-2">
</div>
</div>
更新:在进一步测试中,它似乎在 Chrome 中运行完美,但 Safari 和 FireFox 显示了这个问题。
最佳答案
我没有发现您的代码有任何“错误”。我敢打赌,原因是您的图片有 2.1MB,从 2500px 调整为窗口宽度。考虑到浏览器正在尝试“绘制”图像并计算每个滚动值的位置......
我会在 css 上使用背景位置来处理它,但与您保持一致,问题似乎集中在性能上。你在 JS 上做的事情有点低效,因为首先你选择所有 '*[class^="prlx"]'
循环遍历它们,然后你在每个循环中再次应用到所有它们通过再次寻找它们来重新计算位置。当您遍历元素时,您可以使用 this
元素并对其应用更改。将 $this 保存到一个变量只是为了不在同一个元素上应用 jQuery 两次并节省一点资源,但在这种情况下可能并不那么重要。
在我的笔记本电脑上,我看不到它跳动。尝试使用较小的图像,看看它是否提高了一点性能。
jQuery(document).ready(function() {
jQuery(window).scroll(function() {
jQuery('*[class^="prlx"]').each(function(r) {
var $this = $(this);
var pos = $this.offset().top;
var scrolled = $(window).scrollTop();
$this.css('top', +(scrolled * 0.6) + 'px');
});
});
});
*[class^="prlx"] {
position: absolute;
width: 100%;
height: 300%;
top: 0;
left: 0;
z-index: -1;
background-size: 110%;
}
.prlx-2 {
background-image: url('http://www.roscodigitalmedia.co.uk/rosco/wp-content/uploads/2015/12/bigstock-Artist-Photographer-Retouches-91840682.jpg');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container-fluid homeHeader">
<div class="prlx-2">
</div>
</div>
关于jquery - 视差效果跳跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337128/