我试图让一个 javascript 函数只运行一次。我见过这个问题之前被问过,例如Function in javascript that can be called only once ,但我无法使此处的解决方案起作用。我不确定是不是因为我有嵌套函数,还是我遗漏了什么。本质上,我正在尝试运行一个函数,当滚动网页时,它: - 在标题的 Canvas 上运行一个小动画 - 减小标题的大小 - 就这样吧
但是当有任何后续滚动时,动画会继续重新运行。这是非工作代码的摘要版本:
$(document).on("scroll",function(){
var arrange_title = function(){
//some code
};
if($(document).scrollTop()>0){
arrange_title();
arrange_title = function(){};
setTimeout(function(){
$("header").removeClass("large").addClass("small");
},1000);
}
});
我还尝试声明一个全局变量,在“window.onload”函数中将其设置为“false”,然后在运行动画的 if 函数中将其设置为 true(if 函数仅在变量运行时运行是错误的),但这也不能阻止它。想法?
最佳答案
您正在寻找的是类似于 listenToOnce
的内容,其中监听器触发一次,但再也不会触发。这可以修改为多次调用,但逻辑是这样的:
注册监听器。
然后,一旦监听器触发,将其移除。
参见 .off
$(document).on("scroll",function(){
var arrange_title = function(){
//some code
};
if($(document).scrollTop()>0){
arrange_title();
arrange_title = function(){};
setTimeout(function(){
$("header").removeClass("large").addClass("small");
// $(document).off('scroll'); // or here
},1000);
}
$(document).off('scroll'); // remove listener, you can place this in the setTimeout if you wish to make sure that the classes are added/removed
});
关于javascript - 停止运行不止一次的嵌套 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34515951/