2013-05-05 64 views
0

启停JavaScript函数我有我的网站下面的代码....由定时器

首先,我将如何开始通过单击链接而动画/功能?

然后,我将如何“冻结”动画中的最后一帧? (可能由定时器?)

谢谢。

HTML标记:

<div id="anim"></div> 

CSS:

#anim { 
width: 14px; height: 14px; 
background-image: url(http://mail.google.com/mail/im/emotisprites/wink2.png); 
background-repeat: no-repeat; 
} 

的Javascript:

var scrollUp = (function() { 
    var timerId; // stored timer in case you want to use clearInterval later 

    return function (height, times, element) { 
    var i = 0; // a simple counter 
    timerId = setInterval(function() { 
     if (i > times) // if the last frame is reached, set counter to zero 
     i = 0; 
     element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up 
     i++; 
    }, 100); // every 100 milliseconds 
    }; 
})(); 

// start animation: 
scrollUp(14, 42, document.getElementById('anim')) 

这里有一个小提琴:http://jsfiddle.net/ctF4t/

回答

1

您的代码已经为所制备,读取的第二行:

var timerId; // stored timer in case you want to use clearInterval later 

的setInterval被用来定义在 一定的时间间隔再次并再次运行的功能。 clearInterval用于阻止这一点。在 动画的结束,而不是重置帧计数器i为0,我们可以使用clearInterval 停止动画一起:

 if (i > times) { 
      clearInterval(timerId); 
     } 

这里有一些额外的输出用于调试的小提琴:http://jsfiddle.net/bjelline/zcwYT/

0

喜你可以返回js对象句柄开始和结束..因为timerId充当私人我们不能从外部访问函数。

var scrollUp = (function() { 
    var timerId, height, times ,i = 0 , element; 

    return { 
     stop : function(){ 
      clearInterval(timerId); 
     }, 
     init :function(h, t, el){ 
      height = h; 
      times = t; 
      element =el ; 
     }, 
     start : function () { 
      timerId = setInterval(function() { 
       // if the last frame is reached, set counter to zero 
       if (i > times) { 
       i = 0; 
       } 
       //scroll up   
       element.style.backgroundPosition = "0px -" + i * height + 'px'; 
       i++; 
      }, 100); // every 100 milliseconds 
      } 
    }; 
})(); 

请参阅完整操作http://jsfiddle.net/ctF4t/1/。希望这会帮助你