2012-08-13 38 views
0

基本上,我要求的是對最好的方式進行以下操作的意見;Jquery paralax效果函數

我基本上已經有這個了:http://jsfiddle.net/BnJ3G/1/這或多或少是一個背景動畫,具體取決於滾動事件。類似於一個paralax類型的函數。

我只是想知道,用最少的代碼解決多軸問題的最簡單的方法,我有大約10種不同的東西需要應用這種效果,但目前我僅限於+ x軸,其中因爲我需要(+ X,-X,+ Y和-Y)。有沒有辦法改變這個,這樣我可以在主函數之外做一些簡單的事情?

$('#element1').animatePosX(percentage); 
$('#element2').animateNegY(percentage); 

等...

如果可能的話我很樂意幫助!

回答

0

我花了一段時間才弄清楚簡單地模擬視差滾動的基本數學。這可能不是向網站添加視差的最佳方式,但它目前正在爲我運作。希望這對其他人來說是一個有用的起點。它不會影響大小或模糊或任何東西 - 只有滾動的速度。

// i is id, t is distance from top, d is depth (1-100) 
 
// depth of 50 will scroll at normal scroll speed. 
 
plax = [{ 
 
    "i": "sue", 
 
    "t": 50, 
 
    "d": 90 
 
    }, 
 
    { 
 
    "i": "mark", 
 
    "t": 100, 
 
    "d": 50 
 
    }, 
 
    { 
 
    "i": "janis", 
 
    "t": 500, 
 
    "d": 50 
 
    }, 
 
    { 
 
    "i": "donna", 
 
    "t": 300, 
 
    "d": 1 
 
    } 
 
]; 
 

 

 
$window = $(window); 
 
$(function() { 
 
    $.each(plax, function() { 
 
    eyedee = "#" + this['i']; 
 
    $(eyedee).addClass("plax"); 
 
    m = mathIt(this['d'], this['t']); 
 
    $(eyedee).css({ 
 
     "top": m, 
 
     "z-index": -this['d'] 
 
    }); 
 

 
    }); 
 
    $window.scroll(function() { 
 
    $.each(plax, function() { 
 
     eyedee = "#" + this['i']; 
 
     m = mathIt(this['d'], this['t']); 
 

 
     $(eyedee).css("top", m); 
 
    }); 
 
    }); 
 
}); 
 

 
function mathIt(d, t) { 
 
    return ((((d - 50) * 2)/100) * $(window).scrollTop()) + t; 
 
}
.plax { 
 
    position: absolute; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="sue">here's sue</div> 
 
<div id="mark"> 
 
    <h2>here's mark</h2> 
 
</div> 
 
<div id="donna"> 
 
    <h1>here's donna</h1> 
 
</div> 
 
<div id="janis"> 
 
    <h2>here's janis</h2> 
 
</div>