デモ:http://codepen.io/mo4_9/pen/PGRjoX
動かしたい分だけ大きめの画像を設定
20px大きめの画像
#bg{
width: calc(100% + 20px);
height: calc(100% + 20px);
}
レイヤーを複数重ねて視差効果を生む
const ww = window.innerWidth;
const wh = window.innerHeight;
const hw = ww / 2;
const hh = wh / 2;
const pm = 20; // parallax margin
const $bg = $('#bg');
const $box = $('#box');
$(window).on('mousemove', (e) => {
// 中心から端までの距離を、余分に大きくとった背景画像の分(ここでは20÷2=10px)に割り当てる
const mw = ( e.clientX - hw ) / hw * ( pm / 2 ); // 0.0 ~ 10.0
const mh = ( e.clientY - hh ) / hh * ( pm / 2 );
console.log( mw, mh );
$bg.css('margin-left', mw );
$bg.css('margin-top', mh );
// これでも同じ
// $bg.css('left', hw + mw );
// $bg.css('top', hh + mh );
$box.css('margin-left', mw * -0.5 ); // 逆方向
$box.css('margin-top', mh * 0.5);
})