2016-04-15 66 views
2

我对这个javascript有问题。在我的网站上是一个视差div,它应该滚动,如果我移动我的鼠标。这个脚本到目前为止工作,但它滚动的身体,而不是在视差div,像它应该。Javascript mouse motion parallax 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); 
} 
+3

发表的jsfiddle或使用计算器的javascriot解释 –

+0

小提琴是有用的,但它是因为你调用'.scrollBy()''上window'?这会导致窗口滚动而不是'.parallax' div。 – digglemister

+0

我创建了一个小提琴:https://jsfiddle.net/vfs2rhqL/ 当您移动鼠标时,它应该具有当您使用鼠标滚轮进行滚动时所达到的效果。谢谢。 – Philipp

回答

2

这是因为你正在呼吁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; 

您还可能要当你的鼠标离开窗口重置x和y,否则你可能会得到跳跃,如果,例如,鼠标离开从右侧从左至右,然后重新进入:

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

退房的工作小提琴:https://jsfiddle.net/uw2n0jox/3/

+0

谢谢,它工作! – Philipp

0

使其视差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>