如何根据浏览器滚动y位置而不是按时间调整Greensock.js补间?

Age*_*bra 0 javascript tween greensock

如何根据滚动位置手动调整时间?那可能是什么样的?基本上"滚动"补间?这样补间对滚动鼠标的Y位置做出反应而不是仅根据预设时间触发和执行?

Tah*_*med 5

恕我直言,这是你需要做的:

  1. 您需要TimelineMax来为动画排序.TimelineMax根据您的喜好放置您的动画.
  2. 您需要window事先确定可以向上滚动的最大滚动位置.(这也可以在浏览器调整大小时重新计算,但我在下面的示例中没有考虑到这一点).你可以借助这个答案找出答案.另请阅读有关该答案的评论.
  3. 滚动时,您需要将窗口对象的当前滚动位置转换为以下百分比:var currentScrollProgress=window.scrollY/maxScroll;这样您currentScrollProgress应始终位于0和之间1.
  4. TimelineMax具有progress()其取值范围从方法01其中0作为动画的初始状态和1为最终状态.currentScrollProgress 把它喂进去,你就完成了.
  5. 或者,您可以补间timeline本身即:TweenMax.to(timeline,scrollTweenDuration,{progress:currentScrollProgress,ease:ease});.

我的示例中使用的代码如下:

HTML:

<div>&nbsp;</div>
<div>&nbsp;</div>
...
Run Code Online (Sandbox Code Playgroud)

CSS:

html, body { margin: 0; padding: 0; }
div { width: 100%; height: 60px; margin: 2px 0; }
div:nth-child(odd) { background: #cc0; }
div:nth-child(even) { background: #0cc; }
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

/*global TweenMax, TimelineMax,Power2*/
var myDIVs=document.querySelectorAll('div'),numDIVs=myDIVs.length;
var timeline=new TimelineMax({paused:true}),duration=.4,ease=Power2.easeOut,staggerFactor=.1,scrollTweenDuration=.4;
var scrollTimeout=null,scrollTimeoutDelay=20,currentScrollProgress=0;
var maxScroll=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)-window.innerHeight; //see [https://stackoverflow.com/a/17698713/3344111]
function init(){
    initTimeline();
    listenToScrollEvent();
    onScroll();
}
function initTimeline(){
    for(var i=0; i<numDIVs; i+=1){ timeline.fromTo(myDIVs[i],duration,{opacity:0},{opacity:1,ease:ease},i*staggerFactor); }
}
function listenToScrollEvent(){
    (window.addEventListener)?window.addEventListener('scroll',debounceScroll,false):window.attachEvent('onscroll',debounceScroll);
}
function debounceScroll(){
    clearTimeout(scrollTimeout);
    scrollTimeout=setTimeout(onScroll,scrollTimeoutDelay);
}
function onScroll(){
    currentScrollProgress=roundDecimal(window.scrollY/maxScroll,4);
    //timeline.progress(currentScrollProgress); // either directly set the [progress] of the timeline which may produce a rather jumpy result
    TweenMax.to(timeline,scrollTweenDuration,{progress:currentScrollProgress,ease:ease}); // or tween the [timeline] itself to produce a transition from one state to another i.e. it looks smooth
}
function roundDecimal(value,place){ return Math.round(value*Math.pow(10,place))/Math.pow(10,place); }
//
init();
Run Code Online (Sandbox Code Playgroud)

这是由此产生的jsFiddle.希望能帮助到你.

Ť