gpt4 book ai didi

javascript - 动画时阻止链接切换

转载 作者:行者123 更新时间:2023-11-28 05:48:06 25 4
gpt4 key购买 nike

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

但是我注意到,如果在有内容动画的情况下单击另一个链接,则会出现错误,因此我创建了一个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com