2010-05-22 81 views
1

我试图创建一个循环动画,onmousedown开始并停在onmouseout上。效果是一个简单的滚动,将继续循环,直到你释放鼠标。jQuery动画循环不起作用

我创建了一个执行.animate方法的函数,它将自身作为回调传递,但代码只运行一次。

这里是整个代码:

$(document).ready(function() { 
var $scroller = $("#scroller"); 
var $content = $("#content", $scroller); 

// lineHeight equal to 1 line of text 
var lineHeight = $content.css('line-height'); 

//Amount to scroll = 3 lines of text a time 
var amountToScroll = lineHeight.replace("px","")*3; 
var maxScroll = $content.height() - $scroller.height(); 

function scrollDown() { 
    var topCoord = $content.css("top").replace("px",""); 
    if(topCoord > -maxScroll) { 
     if((-maxScroll-topCoord) > -amountToScroll) { 
      $content.stop().animate({ 
       top: -maxScroll 
      }, 1000 
      ); 
     } 
     else { 
      $content.stop().animate({ 
       top: "-=" + amountToScroll 
      }, 1000, 
      function(){ 
       scrollDown() 
      } 
      ); 
     } 
    } 
} 

function scrollUp() { 
    var topCoord = $content.css("top").replace("px",""); 
    if(topCoord < 0) { 
     if(topCoord > -amountToScroll) { 
      $content.stop().animate({ 
       top: 0 
      }, 1000 
      ); 
     } 
     else { 
      $content.stop().animate({ 
       top: "+=" + amountToScroll 
      }, 1000, 
      function(){scrollUp()} 
      ); 
     } 
    } 
} 

$("#scroll-down").mousedown(function() { 
    scrollDown(); 
}); 

$("#scroll-down").mouseup(function() { 
    $content.stop(); 
}); 

$("#scroll-up").mousedown(function() { 
    scrollUp(); 
}); 
$("scroll-up").mouseup(function() { 
    $content.stop(); 
}); 
}); 

回答

2

你有没有试图消除stop()电话?

function scrollDown() { 
    var topCoord = parseInt($content.css("top").replace("px","")); 
    if(topCoord > -maxScroll) { 
     if((-maxScroll-topCoord) > -amountToScroll) { 
      $content.animate({ 
       top: -maxScroll 
      }, 1000 
      ); 
     } 
     else { 
      $content.animate({ 
       top: "-=" + amountToScroll 
      }, 1000, scrollDown 
      ); 
     } 
    } 
} 

您不需要停止,因为只有在当前动画结束后动画才会排队。

此外,它到达底部后,它应该再次向上滚动然后再滚下去?

+0

谢谢@sirhc - 这是干扰(),是干扰。虽然我想在按下鼠标的同时保持滚动,但如果有人多次单击按钮,我不想建立队列。有没有解决的办法? – Marko 2010-05-22 23:58:59

+0

查看['.stop()'](http://api.jquery.com/stop/)的文档。给出一个例子。你可能需要使用'stop(true,true)'。 但是,因为您正在循环播放动画,所以无法在动画播放之前使用它,否则它将无限次地重现。尽管你可以在'mouseup'上使用它。 – sirhc 2010-05-23 13:52:05

1

当你说“scroll”时,你是否在讨论带有滚动条的元素的实际滚动位置(就像现在可能在本页右侧的那个)?

如果这就是你的意思,jQuery有一个scrollTop()方法可以用来获取和设置滚动位置。

var topCoord = $content.scrollTop(); 

... 

$content.animate({ 
      scrollTop: "+=" + amountToScroll 
     }, 1000, 
     function(){scrollUp()} 
     ); 

这将移动内容的滚动条位置。

不知道这是否是你想要做什么,或者如果它更是一个滑块,其中scroller剪辑content不使用滚动条,所以你需要真正的移动内容的顶部坐标..