在此代码中,在正文滚动时开始更改背景位置。我想在滚动显示在背景图像上时更改背景位置
$(function() {
var rotator = $('#rotator');
var container = $(document);
var viewport = $(window);
var images = 72;
var imageHeight = 30000 / images;
var scrollHeight = container.height() - viewport.height() + imageHeight;
var step = images / scrollHeight;
viewport.scroll(function(event) {
var x = -Math.floor(step * viewport.scrollTop()) * imageHeight;
rotator.css('background-position', x + 'px 0');
});
});
body {
height: 2000px;
}
#rotator {
font-size: 416px;
width: 1em;
height: 1em;
position: relative;
top: 580px;
right: 0;
z-index: -1;
background: transparent url(https://www.3sessanta.it/images/polaroid/sprite_polaroid_total.jpg) no-repeat 0 0;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rotator"></div>
答案 0 :(得分:1)
您需要在后台更改开始if (viewport.scrollTop() > fixed_value)
时添加条件,然后您需要从计算中删除此相同值,如下所示:
$(function() {
var rotator = $('#rotator');
var container = $(document);
var viewport = $(window);
var images = 72;
var imageHeight = 30000 / images;
var scrollHeight = container.height() - viewport.height() + imageHeight;
var step = images / scrollHeight;
viewport.scroll(function(event) {
if (viewport.scrollTop() > 580) {
var x = -Math.floor(step * (viewport.scrollTop() - 580)) * imageHeight;
rotator.css('background-position', x + 'px 0');
}
});
});
body {
height: 2000px;
}
#rotator {
font-size: 416px;
width: 1em;
height: 1em;
position: relative;
top: 580px;
right: 0;
z-index: -1;
background: transparent url(https://www.3sessanta.it/images/polaroid/sprite_polaroid_total.jpg) no-repeat 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rotator"></div>