视差鼠标移动效果如何纯javascript

how do parallax mouse move effect pure javascript

如何实现像this example:

这样的视差效果

但是 没有 使用 jQuery,使用纯 javascript 并且只有图像?

$(document).ready(function(){
  $('#landing-content').mousemove(function(e){
    var x = -(e.pageX + this.offsetLeft) / 20;
    var y = -(e.pageY + this.offsetTop) / 20;
    $(this).css('background-position', x + 'px ' + y + 'px');
  });    
});
#landing-content {
 overflow: hidden;
 background-image: url(http://i.imgur.com/F2FPRMd.jpg);
 width: 100%;
 background-size: 150% 150%;
 background-repeat: no-repeat;
 max-height: 500px;
 border-bottom: solid;
 border-bottom-color: #628027;
 border-bottom-width: 5px;
}

.slider {
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  padding-top: 200px;
  max-width: 1002px;
}

.slider img {
 width: 80%;
 padding-left: 10%;
 padding-right: 10%;
 height: auto;
 margin-left: auto;
 margin-right: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="landing-content">
    <section class="slider"> 
        <img src="http://i.imgur.com/fVWomWz.png"/>
            
    </section>
</div>

注意:与示例中一样,元素应在鼠标方向上平滑移动。

您可以根据控制背景位置的 clientX/clientY 坐标更新两个自定义属性,就像在这个概念证明中一样

Codepen demo


CSS

:root {
  --mouseX: 50%;
  --mouseY: 50%;
}

body {
  min-height: 100vh;
  background-size: auto 150%;
  background-position: var(--mouseX) var(--mouseY);
  background-repeat: no-repeat;
  background-image: url(..);
}

JS

let dde = document.documentElement;
dde.addEventListener("mousemove", e => {
  let ow = dde.offsetWidth; 
  let oh = dde.offsetHeight; 
  dde.style.setProperty('--mouseX', e.clientX * 100 / ow + "%");
  dde.style.setProperty('--mouseY', e.clientY * 100 / oh + "%");
});

在这个例子中,我使用了一张在高度上覆盖整个视口但非常大的图像。在初始状态下,背景居中。

在 JS 中的 mousemove 事件中,您获取鼠标的坐标(例如 clientXclientY)并设置一个 CSS 自定义 属性 (--mouseX/--mouseY) 与该值,用于背景定位。

我只是 'translated' 将 jQuery 代码直接转换为普通 JS

//Call in document load event
document.getElementById("landing-content")
.addEventListener('mousemove', function(e) {
  var x = -(e.pageX + this.offsetLeft) / 20;
  var y = -(e.pageY + this.offsetTop) / 20;
  e.currentTarget.style.backgroundPosition = x + 'px ' + y + 'px';
})
#landing-content {
  overflow: hidden;
  background-image: url(http://i.imgur.com/F2FPRMd.jpg);
  width: 100%;
  background-size: 150% 150%;
  background-repeat: no-repeat;
  max-height: 500px;
  border-bottom: solid;
  border-bottom-color: #628027;
  border-bottom-width: 5px;
}

.slider {
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  padding-top: 200px;
  max-width: 1002px;
}

.slider img {
  width: 80%;
  padding-left: 10%;
  padding-right: 10%;
  height: auto;
  margin-left: auto;
  margin-right: auto;
}
<div id="landing-content">
  <section class="slider"> 
    <img src="http://i.imgur.com/fVWomWz.png">
  </section>
</div>