2016-04-15 122 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>