javascript - bxSlider onAfterSlide 回调

标签 javascript jquery image bxslider

大家早上好 :) 我遇到了一个问题,我的脖子已经痛了 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/

相关文章:

jquery - 在新打开的浏览器窗口上附加 CSS

javascript - Jquery 仅根据依赖的选择下拉菜单触发一次

javascript - 在 IE7/8 中将 excanvas 元素保存为图像

image - 设置内容模式 : for HJManagedImageV is not working for iOS

javascript - shelljs - 获取由 shelljs.exec() 进程创建的进程的进程 ID

javascript - 加载数据时读取缓冲区

javascript - 一个对象是否可以在直接访问时只有一个值,并且在内部嵌套对象?

javascript - 使用 jQuery 确定元素的类

html - CSS 使图像 float 在描述列表项的右侧

javascript - onClick 事件 - 一次只有一个事件