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