div要素で作る簡単なパララックス効果

Ads

Result

jQuery

//PARALLAXY by roXon
distance = 70;
sensitivity = 7;

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); 
    layer.animate({top: '-' + pixPosHalf}, 0); 
    
    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);
    });

    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);

});

$('.box').click(function() {
    $(this).toggleClass('green');
});

css

#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;
}

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>

via

jQuery; Parallax page – Get the click event go through DIV layers

タイトルとURLをコピーしました