我试图创建一个循环动画,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();
});
});
谢谢@sirhc - 这是干扰(),是干扰。虽然我想在按下鼠标的同时保持滚动,但如果有人多次单击按钮,我不想建立队列。有没有解决的办法? – Marko 2010-05-22 23:58:59
查看['.stop()'](http://api.jquery.com/stop/)的文档。给出一个例子。你可能需要使用'stop(true,true)'。 但是,因为您正在循环播放动画,所以无法在动画播放之前使用它,否则它将无限次地重现。尽管你可以在'mouseup'上使用它。 – sirhc 2010-05-23 13:52:05