javascript - 动画时阻止链接切换

标签 javascript jquery

我的代码有一个小问题,但找不到解决方案。在我的页面中,有一个带有链接的顶栏(主页、关于、注册),每个链接都有自己的内容。假设用户当前正在查看“主页”内容,然后单击“关于”,页面应该隐藏“主页”内容,然后显示“关于”内容。

但是我注意到,如果在有内容动画的情况下单击另一个链接,则会出现错误,因此我创建了一个名为 AllowLinkSwitch 的变量,以阻止用户切换到另一个链接(如果仍然存在动画)动画正在进行中。

this.ContentHideThenShow = function(contentHide, contentShow, contentShowHeight) 
{
    this.AllowLinkSwitch = false;
    $(contentHide).animate({
        height: "0px"
    }, 300, function(){
        $(contentHide).hide();
        $(contentShow).show();
        $(contentShow).animate({
            height: contentShowHeight
        }, 300, function(){ this.AllowLinkSwitch = true; });
    });
}

首先,我在调用函数时将 AllowLinkSwitch 设置为 false,然后在动画结束时将其设置为 true,但变量是永远不会设置回 true 并且我无法切换到其他链接,只有当我将 this.AllowLinkSwitch = true; 行放在 animate 函数之外时,上述代码才有效,但我不希望它像那样工作,因为该错误仍然发生,我需要在动画结束后将该变量设置为 true,有人可以帮忙吗?

最佳答案

animate() 回调中,this 不会是对外部对象的相同引用。您需要将引用存储在该函数之外。试试这个:

this.ContentHideThenShow = function(contentHide, contentShow, contentShowHeight) {
    var _this = this; // store reference here
    _this.AllowLinkSwitch = false;
    $(contentHide).animate({
        height: "0px"
    }, 300, function() {
        $(contentHide).hide();
        $(contentShow).show().animate({
            height: contentShowHeight
        }, 300, function(){ 
            _this.AllowLinkSwitch = true;  // use here
        });
    });
}

或者,您可以通过使用 if (!$(contentShow).is(':animated')) 检查元素当前是否处于动画状态,从而完全避免使用动画状态标志防止逻辑在代码中需要的地方出现。

关于javascript - 动画时阻止链接切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38313570/

相关文章:

javascript - JS/jQuery 返回相关 TD 的 TH,可能吗?

javascript - 在 React 中渲染数组中的特定元素

javascript - 你能在 .babelrc 中使用正则表达式吗?

javascript - 解码多维数组并插入到mysql中

javascript - 创建要绘制的网格

javascript - JQuery 用户界面 : How to remove Icon from specific Accordion group?

javascript - 为什么 jQuery 对象的属性初始化为空?

javascript - Div 悬停无法正常工作

javascript - Rails turbolinks 问题与 window.onload

javascript - 将 JS 函数转换为 jQuery