大家早上好 :) 我遇到了一个问题,我的脖子已经痛了 2 天了。我正在使用 bxSlider 使图像在页面上滑动,并在 onAfterSlide 回调中调用我自己的函数。除了一件事,一切都很好。当我在幻灯片之间快速切换时,我的函数被调用了 2-3 次(页面上有 3 张图像),这不好,因为它会返回意外结果。我不能使用最新版本的 bxSlider,因为标记已更改。我认为会发生这种情况,因为调用 onAfterSlide 回调时动画仍未完成。 这就是我调用 bxSlider 的方式:
$('#slider_bx').bxSlider({
mode: 'fade',
speed: 1000,
pause: 9000,
auto: true,
autoControls: false,
prevText: '',
nextText: '',
autoHover: true,
captions: false,
pager: true,
onBeforeSlide: function () {
if ($('.slide_in').length) {
$('.slide_in').hide();
}
},
onAfterSlide: function () {
if ($('.slide_in').length && $('.slide_in').is(':hidden')) {
doCrazyStuff();
}
}
});
这是我的职能:
function doCrazyStuff() {
var $this = $('.slide_in');
if ($this.length > 0) {
setTimeout(function () {
$this.show();
$this.rotate({
duration: 2000,
angle: 90,
animateTo: -20
});
}, 3000);
}
}
感谢任何帮助。谢谢。
编辑:
我尝试添加 .stop()
,但没有帮助。
$this.show().stop();
$this.stop().show();
$this.stop().rotate({
duration: 2000,
angle: 90,
animateTo: -20
});
$this.rotate({
duration: 2000,
angle: 90,
animateTo: -20
}).stop(); // throws an error
最佳答案
您可以取消超时或检查它是否正在运行。
如果您只想运行最后一次超时:
var crazyTimeout;
function doCrazyStuff() {
var $this = $('.slide_in');
if ($this.length > 0) {
if (crazyTimeout != undefined) {
clearTimeout(crazyTimeout); // Cancel previous timeout
}
crazyTimeout = setTimeout(function () {
crazyTimeout = undefined;
$this.show();
$this.rotate({
duration: 2000,
angle: 90,
animateTo: -20
});
}, 3000);
}
}
如果您只希望第一次超时运行:
var crazyTimeout;
function doCrazyStuff() {
var $this = $('.slide_in');
if ($this.length > 0) {
if (crazyTimeout != undefined) {
return; // A timeout is still running: don't create new one
}
crazyTimeout = setTimeout(function () {
crazyTimeout = undefined;
$this.show();
$this.rotate({
duration: 2000,
angle: 90,
animateTo: -20
});
}, 3000);
}
}
关于javascript - bxSlider onAfterSlide 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13986855/