ユーザーがスクロールするときに background-position と top プロパティを変更しようとしています。背景の固定位置とスプライトの視差をシミュレートしたいので、次のことを行いました。
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では完全にぎくしゃくしています...ページをスクロールする前にコードを強制的に実行する方法はありますか?
どうも :)