我误解了@goddfree在下面发布的内容。他的解决方案完美无缺,我做的唯一改变就是设置isDone回到true被置于animate函数的回调中,如下所示:
$.when($('#carousel_ul_' + unique_id + ' li:last').clone().insertBefore('#carousel_ul_' + unique_id + ' li:first'), $('#carousel_ul_' + unique_id).css('left', '-=' + displace_width + 'px')).done($('#carousel_ul_' + unique_id + ':not(:animated)').animate({left: '+=' + scroll_width + 'px'}, 400, function(){$('#carousel_ul_' + unique_id + ' li:last').remove(); is_done = true; }));
这是一个非常优雅的解决方案,谢谢@goddfree
答案 0 :(得分:0)
HTML锚标签也有onClick事件。你尝试过这样的事吗?从这里你可以使用你找到的解决方案。
<a href="#" onclick='carousel("left", 99335)'><!--stuff here--></a>
<强>更新强>
我认为这可能就是你要找的东西。假设你有三个按钮(我只是编造carousel
个参数,我不知道它们是什么意思):
<a href="#" onclick='carousel("left", 99335)'>Button 1</a>
<a href="#" onclick='carousel("right", 69235)'>Button 2</a>
<a href="#" onclick='carousel("left", 91235)'>Button 3</a>
我们添加一个名为isDone
的变量来检查是否有任何进程在运行。像这样修改carousel
函数(我用注释解释修改):
//isDone is initially set to true, because nothing is running.
var isDone = TRUE;
function carousel(direction, unique_id) {
//First of all, we can only execute the function is isDone is true. So we check for that:
if(isDone) {
//This implements the moment the function is called. We now know that it is currently in progress.
isDone = FALSE;
//This is the same as you had before
if (direction == 'right') {
$(document).ready(function(){
var displace_width = $('#carousel_ul_' + unique_id + ' li:last').outerWidth(true);
var scroll_width = $('#carousel_ul_' + unique_id + ' li:first').outerWidth(true);
//Here we set isDone equal to true when the .done is called:
$.when($('#carousel_ul_' + unique_id + ' li:last').clone().insertBefore('#carousel_ul_' + unique_id + ' li:first'), $('#carousel_ul_' + unique_id).css('left', '-=' + displace_width + 'px')).done(isDone = TRUE; $('#carousel_ul_' + unique_id + ':not(:animated)').animate({left: '+=' + scroll_width + 'px'}, 400, function(){$('#carousel_ul_' + unique_id + ' li:last').remove(); }));
});
} else {
$(document).ready(function(){
var displace_width = $('#carousel_ul_' + unique_id + ' li:first').outerWidth(true);
var scroll_width = $('#carousel_ul_' + unique_id + ' li:nth-child(2n)').outerWidth(true);
//Same thing here
$.when($('#carousel_ul_' + unique_id + ' li:first').clone().insertAfter($('#carousel_ul_' + unique_id + ' li:last'))).done(isDone = TRUE; $('#carousel_ul_' + unique_id + ':not(:animated)').animate({left: '-=' + scroll_width + 'px'}, 400, function(){$('#carousel_ul_' + unique_id + ' li:first').remove(); $('#carousel_ul_' + unique_id).css('left', '+=' + displace_width + 'px'); }));
});
}
}
//If isDone is not true, then we tell the user that and don't execute anything:
else {
alert("Not so fast! There is a process currently in progress.");
}
}
这样,因为所有按钮都调用相同的carousel
函数,所以只有在isDone
设置为true时才会执行它们。否则,用户将收到错误警报,不会发生任何事情。