我正在尝试在用户滚动时更改背景位置和顶部属性。我想模拟精灵的背景和视差的固定位置,所以我做了以下事情:
HTML 部分
<section id="first" data-type="background" data-speed="1">
<div id="sprite1" data-type="sprite" data-speed="-1.5"></div>
<div id="sprite2" data-type="sprite" data-speed="-1"></div>
</section>
<section id="second" data-type="background" data-speed="1">
</section>
CSS 部分
section {
width: 100%;
height: 1000px;
position: relative;
}
#first {
background: url('../img/bg1.png'), no-repeat, fixed, 50% 0;
}
#second {
background: url('../img/bg2.png'), no-repeat, fixed, 50% 0;
}
#sprite1 {
position: relative;
background: url('../img/sprite1.png'), no-repeat, fixed, 50% 0;
width: 100px;
height: 100px;
top: 550px;
left: 100px;
}
#sprite2 {
position: relative;
background: url('../img/sprite2.png'), no-repeat, fixed, 50% 0;
width: 200px;
height: 200px;
top: 650px;
left: 150px;
}
JS部分
$(document).ready(function() {
/* Initialisation */
var $window = $(window);
var offset = 0;
$('section[data-type="background"]').each(function(index) {
var $this = $(this);
console.log($this);
$this.data('data', {
height: $this.height() + offset,
speed: parseFloat($this.attr('data-speed'))
});
offset = $this.data('data').height;
});
$('div[data-type="sprite"]').each(function(index) {
var $this = $(this);
$this.data('data', {
xPosition: parseInt($this.css('top').replace(/px/, '')),
yPosition: parseInt($this.css('left').replace(/px/, '')),
speed: parseFloat($this.attr('data-speed'))
});
console.log($this.data('data'));
});
$('#first').data('position', '0');
$(window).scroll(function(){
console.log($(this));
var scrollPos = parseInt($window.scrollTop());
$('section[data-type="background"]').each(function(index) {
var $this = $(this);
$this.css('background-position', '50% ' + (scrollPos / $this.data('speed') + $this.data('data').height) + 'px');
});
$('div[data-type="sprite"]').each(function(index) {
var $this = $(this);
$this.css('top', ((scrollPos / $this.data('data').speed) + $this.data('data').xPosition) + 'px');
});
});
});
你可以在这里看到结果
在 Firefox 上没有问题,背景似乎是固定的,但在 Chrome 上,浏览器似乎从滚动页面开始,然后执行代码。所以它在 Chrome 上完全被吓到了......有没有办法在页面滚动之前强制执行代码?
谢谢 :)