divをパララックス
HTML
<div id="par">
<div class="layer l1">
<div class="box" style="margin-left:100px;">1</div>
</div>
<div class="layer l2">
<div class="box" style="margin-left:200px;">2</div>
</div>
<div class="layer l3">
<div class="box" style="margin-left:300px;">3</div>
</div>
</div>
CSS
body{background:#eee;font-size:12px;}
#par{
position:relative;
/*overflow:hidden;*/
margin:150px auto;
width:400px;
height:200px;
background:#fff;
}
.layer{
position:absolute;
width:100%;
height:100%;
border:1px solid #000;
}
.box{
position:relative;
width:50px;
height:50px;
background:#f00;
margin:10px;
padding:5px;
z-index: 2;
}
.green{
background:#cf5;
}
JavaScript
//PARALLAXY by roXon
//##### SET LAYERS DISTANCE AND SENSITIVITY ###########
distance = 30;
sensitivity = 17;
//##############################
var distHalf = distance / 2;
var parW = $('#par').width(),
parH = $('#par').height();
$('.layer').each(function() {
var layer = $(this);
pixPos = distance * (layer.index() + 1);
pixPosHalf = distHalf * (layer.index() + 1);
layer.width('+=' + pixPos);
layer.height('+=' + pixPos);
layer.animate({left: '-' + pixPosHalf }, 0); // just to remove shock on page load
layer.animate({top: '-' + pixPosHalf}, 0); // just to remove shock on page load
wDiff1 = $('#par').width();
hDiff1 = $('#par').height();
wDiff2 = layer.width();
hDiff2 = layer.height();
var wDiff = ((wDiff2 / wDiff1) - 1).toFixed(2);
var hDiff = ((hDiff2 / hDiff1) - 1).toFixed(2);
$('#par').mousemove(function(mousEv) {
parOffset = $(this).offset();
mouseX = (mousEv.pageX - parOffset.left);
mouseY = (mousEv.pageY - parOffset.top);
});
// for mouse and layers start pos
var parWhalf = parW / 2,
parHhalf = parH / 2;
var mouseX = parWhalf,
mouseY = parHhalf;
var posX = parWhalf,
posY = parHhalf;
//#
setInterval(function() {
posX += (mouseX - posX) / sensitivity;
posY += (mouseY - posY) / sensitivity;
layer.css({
left: '-' + Math.round(posX * wDiff) + 'px',
top: '-' + Math.round(posY * hDiff) + 'px'
});
}, 30);
});
//###################### END
$('.box').click(function() {
$(this).toggleClass('green');
});