jQuery元素的位置绝对改变滚动顶部



Hi我需要位置来使fixed background具有绝对位置并在滚动更改顶部。但我的div一直在跳,就像演示中的一样

有人知道为什么吗?

您的问题是滚动位置的delta计算。您需要使用container的固定顶部值,而不是视差图像本身。

这个例子应该适用于一些小的性能改进

var $window = $(window);
$window.on('scroll', pi);
function pi() {
$('.parallax-image').each(function(index, element) {
var $element= $(element);
$element.css('top', parseInt($window.scrollTop()) - parseInt($element.parent().offset().top));
});
}
.container {
position: relative;
display: block;
width: 100%;
height: 200px;
overflow: hidden;
}
.parallax-image {
width: 100vw;
height: 100vh;
position: absolute;
left: 0;
top: 0;
background: url("https://htmlcolorcodes.com/assets/images/html-color-codes-color-tutorials-hero-00e10b1f.jpg") no-repeat center center;
background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>First Test</p>
<div class="container">
<div class="parallax-image"></div>
</div>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Second Test</p>
<div class="container">
<div class="parallax-image"></div>
</div>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Third Test</p>
<div class="container">
<div class="parallax-image"></div>
</div>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>

补充

如果你愿意,你可以使用纯CSS的视差图像。你可以在w3schools找到一个例子。

最新更新