たった数行でパララックス(視差効果)を実装する方法【jQuery】


WEBページの表現方法のひとつ「パララックス」の実装方法を紹介。
- コンテンツのボリュームがそれほど多くない。
- シンプルに実装したい
そんな人向けの内容となっています。
パララックスとは?
スクロールすると、背景や画像・テキストが時間差で移動して見える事で起きる「視差効果」による奥行きを表現するテクニックです。
これが実にシンプルに実装できてしまうんですね。
ここでは、比較的かんたんにパララックスが演出できるかなりシンプルなコードを紹介します。
パララックスのサンプルコード
HTML
<div id="parallax-bg1" class="bg_container">
<!-- 空 -->
</div>
<div id="parallax-bg2" class="bg_container">
<img src="images/anthropomorphic-1297542_640.png" alt="" width="400" />
</div>
<div id="parallax-bg3" class="bg_container">
<img src="images/rocket-1717160_640.png" alt="" width="500" />
</div>
CSS
.bg_container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#parallax-bg1 {
z-index: 1;
background: url(images/milky-way-1049493_s.jpg) center 0 / cover;
}
#parallax-bg2 {
z-index: 2;
}
#parallax-bg2 img {
position: absolute;
left: 40%;
top: 20%;
}
#parallax-bg3 {
z-index: 3;
}
#parallax-bg3 img {
position: absolute;
left: 60%;
top: 90%;
}
JS
$(window).bind('scroll',function(e){
parallaxScroll();
});
function parallaxScroll(){
var scrolled = $(window).scrollTop();
$('#parallax-bg1').css('background-position-y', ( 0 - (scrolled * 0.1)) + 'px');
$('#parallax-bg2').css('top', ( 0 - (scrolled * .25) ) + 'px');
$('#parallax-bg3').css('top', ( 0 - (scrolled * .5) ) + 'px');
};



