Javascript鼠标移动视差div

Javascript mouse movement parallax div

我对此有疑问javascript。在我的网站上有一个视差 div,如果我移动鼠标它应该会滚动。该脚本到目前为止有效,但它在 body 上滚动,而不是在视差 div 上滚动,就像它应该的那样。

var x, y;
function handleMouse(e) {
  if (x && y) {
    window.scrollBy(e.clientX - x, e.clientY - y);
  }
  x = e.clientX;
  y = e.clientY;
}
document.onmousemove = handleMouse;

HTML

        <div class="parallax">
            <div class="parallax__layer parallax__layer--deep">
                <img id="background" src="img/deep.png">
            </div>
            <div class="parallax__layer parallax__layer--back">
                <img id="blatt" src="img/back.png">
            </div>
            <div class="parallax__layer parallax__layer--base">
                <img id="farn" src="img/base.png">
            </div>
            <div class="parallax__layer parallax__layer--ground">
                <div id="faul">
                    <img id="sloth" src="img/y3oVSt2.png">
                </div>
            </div>
        </div>

CSS

.parallax {
   perspective: 1px;
   height: 150vh;
   overflow-x: scroll;
   overflow-y: scroll;
   margin-left: -730px;
   margin-top: -300px;
}
.parallax__layer img {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

.parallax__layer--ground {
    transform: translateZ(0px);
}
.parallax__layer--base {
    transform: translateZ(0px);
}
.parallax__layer--back {
    transform: translateZ(-5px) scale(2);
}
.parallax__layer--deep {
    transform: translateZ(-10px) scale(5);
}

这是因为您在 window 上呼叫 .scrollBy()。相反,您想调整 .parallax div:

.scrollTop.scrollLeft 属性
var speed = 5 //adjust to change parallax scroll speed
var x, y;
function handleMouse(e) {
  if (x && y) {
    document.getElementsByClassName("parallax")[0].scrollTop += speed*(e.clientY - y);
    document.getElementsByClassName("parallax")[0].scrollLeft += speed*(e.clientX - x);
  }
  x = e.clientX;
  y = e.clientY;
}
document.onmousemove = handleMouse;

您可能还想在鼠标离开 window 时重置 x 和 y,否则,如果鼠标从左侧离开然后从右侧重新进入,您可能会跳转:

document.onmouseleave = function() {
  x = undefined;
  y = undefined;
}

检查工作 fiddle:https://jsfiddle.net/uw2n0jox/3/

固定视差div。 像这样....因为你必须让它在视差 div.

上滚动
<div class="bg" style="background:url('image/banner.png') repeat;position:fixed;width: 100%;height:300%;top:0;left:0;z-index:-1;"> </div>