我有一个简单的JavaScript内容滑块,它显示纯文本。它工作得相当好,除非你点击上一个和下一个太快。它很难完全复制,但如果你随机地反复点击,会发生两件奇怪的事情:
1.空白幻灯片将间歇性地出现并且..
1.两张幻灯片将重叠在一起,如有任何帮助,将不胜感激。
http://jsfiddle.net/n52xmwLn/
// Testimonials
var thisItem = 1, nextItem = 0, range = 0
//for each content item, set an id, and hide.
$('.testimonial-item').each(function () {
nextItem++;
$(this).attr('id', nextItem).hide();
});
//range contains how many content items exist
range = nextItem, nextItem = 2, prevItem = range;
//display the first content item
thisHeight = $('#' + thisItem).height();
$('#' + thisItem).show();
$('.testimonials').css('height', thisHeight);
//hide old content item, show next item, resize content container
$('.testimonial-control.next').click(function () {
prevItem = thisItem;
//get height of next content item to resize container
thisHeight = $('#' + nextItem).height();
//resize content container
$('.testimonials').animate({
height: (thisHeight + 'px')
}, 250, 'swing');
//hide old content item
$('#' + thisItem).fadeToggle(500, "linear");
//show next content item
$('#' + nextItem).fadeToggle(500, "linear");
//set old content item to current item
thisItem = nextItem;
//loop to first item if range reached
if (thisItem >= range) {
nextItem = 1; prevItem = range - 1;
} else {
nextItem++; prevItem = thisItem - 1;
}
});
//end next click function
//hide current content item, resize content container, show previous item
$('.testimonial-control.prev').click(function () {
//If we have reached the end range, the next item will be item #1
if (nextItem == 1) {//so set the current item to the last
thisItem = range;
} else thisItem = nextItem - 1;
//get height of next content item to resize container
thisHeight = $('#' + prevItem).height();
//resize content container
$('.testimonials').animate({
height: (thisHeight + 'px')
}, 250, 'swing');
//hide old content item
$('#' + thisItem).fadeToggle(500, "linear");
//show next content item
$('#' + prevItem).fadeToggle(500, "linear");
//set next content item to current item
nextItem = thisItem;
if (prevItem >= range) {//if at end of items
nextItem = 1;//first
prevItem = range - 1;
thisItem = range;
} else if (prevItem <= 1) {//if at start of items
prevItem = range;
thisItem = 1;
nextItem = 2;
} else {//if in the middle of items
prevItem--;
thisItem--;
}
});
//结束前一次点击功能
2条答案
按热度按时间rlcwz9us1#
这很可能是因为动画/淡入淡出切换代码在另一次点击发生之前没有完成。
你应该阻止你的点击功能的处理,直到动画完成。为了实现这一点,我会做以下事情:
添加一个全局布尔变量来跟踪动画的状态,比如..
var animating = false;
将所有的click函数 Package 在一个if块中,这样它们就不会运行if
animating
为true。在块if( ! animating ) { animating = true; ... }
中也将animating
设置为true最后一步是在
fadeToggle
的完整回调中将animating
设置为false:$('#' + thisItem).fadeToggle(500, "linear", function() { animating = false; });
5q4ezhmt2#
您需要将
.stop()
和.stopPropagation()
添加到所有动画函数中,以防止它们彼此“冲突”:JSFiddle另外,不要忘记你的CSS中的结束括号
}
,它会把一切都搞砸。