2
我试图在用户滚动时更改背景位置& top属性。我想模拟背景和视差雪碧一个固定的位置,所以我做了以下内容:javascript scroll上的延迟 - Chrome
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');
});
});
});
你可以看到结果here
在Firefox上是没有问题的,背景似乎固定的,但在Chrome,它似乎是浏览器通过滚动页面开始并执行该代码后。所以它完全在Chrome上被猛拉... 有没有什么办法在页面滚动之前强制执行代码?
THX :)
嗨,thx回答!其实我的问题并不是指滚动动画,而是在用户滚动时“跳动”背景效果。看看空白方块的顶部,看起来Chrome浏览器首先滚动页面,然后执行回调。这是预期的行为,根据它的回调定义,但在Chrome中,性能非常差,导致首先显示页面滚动并执行后台位置更改。国际海事组织的问题在这里,这就是为什么它是抽搐,但我很惊讶这种行为... – Pcriulan