Parallax эффект

07 Декабря 2019 01:33 (Редактировано: 07 Декабря 2019 01:52)

HTML

<div class="parallax"> 
    <div data-speed="10" class="layer far"></div>
    <div data-speed="40" class="layer mid"></div>
    <div data-speed="80" class="layer close"></div>
</div>

CSS

img {
    max-width:  100%;
}
header {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    justify-content: center;
    -ms-align-items:    center;
    align-items:    center;
    height: 100vh;
}
.parallax {
    z-index: -1;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    min-height: 100vh;
}
.layer {
    position: absolute;
    left: -10%;
    top: 0;
    width: 110%;
    height: 100%;
}
.layer.far {
    background: url(images/far.png);
    background-size: cover;
}
.layer.mid {
    background: url(images/mid.png);
    background-size: cover;
}
.layer.close {
    background: url(images/close.png);
    background-size: cover;
}

JS

function parallax(e) {
    this.querySelectorAll('.layer').forEach(item => {
        let speed = layer.getAttribute('data-speed');
        layer.style.transform = 'translateX(' + e.clientX*speed/1000 + 'px)';
    });
}
document.addEventListener('mousemove', parallax);