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

时间:2019-05-07 15:17:39

标签: javascript css parallax

如何实现像this example这样的视差效果:

但是使用null,使用纯JavaScript并仅使用图像?

jQuery
$(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;
}

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

2 个答案:

答案 0 :(得分:0)

您可以根据 ID Code Description 1 A test1 2 B test2 3 C test3 坐标来更新两个自定义属性,这些属性控制着背景的位置,例如在本概念证明中

  

Codepen demo


CSS

clientX/clientY

JS

: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(..);
}

在此示例中,我使用了一个图像,该图像覆盖了整个视口的高度,但确实很大。在初始状态下,背景居中。

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中,您将获得鼠标的坐标(例如mousemoveclientX),并使用该值设置CSS自定义属性(clientY) ,用于背景定位。

答案 1 :(得分:0)

我刚刚将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>

相关问题