[英]Limit a function to firing once before being reset
我有以下功能監視滾動位置和觸發功能(在Iscroll4中)。
bgFadeToggle()函數基本上觸發一個顯示/隱藏菜單的函數。 它包含一個存儲向上/向下狀態的變量,以便在滾動期間僅觸發一次相同的功能。
我遇到的問題是,如果用戶合理地快速上下滾動,這些功能會不斷觸發 - 這會使喜劇在屏幕上產生跳舞效果! 任何人都可以推薦一種方法,在一定的時間內將忽略重復的調用,以避免這個問題嗎?
onScrollMove: function() {
var thisScrol = myScroll.getScrollY()
if (thisScrol < -80 ){
bgfadeToggle('on');
}
if (thisScrol > -80){
bgfadeToggle('off');
}
},
bfFadeToggle代碼 -
function bgfadeToggle(which){
if (which == "on" && first == "yes"){
//alert('on yes') ;alert(first)
setTimeout(function() {first="no";$('#wrapper').addClass('hov'); }, 10)
$('.appearLate').fadeIn('500');
$('.footer').animate({
bottom: [ "-40", "swing" ],
opacity: "0"
}, 100, "linear");
$( ".appearLate" ).animate({
top: [ "30", "swing" ],
opacity: "1"
}, 1000, "linear");
}
if (which == "off" && first== "no"){
//alert('off no') ;alert(first)
setTimeout(function() {first="yes";$('#wrapper').removeClass('hov'); }, 10)
$( ".appearLate" ).animate({
top: [ "-55", "swing" ],
}, 1300, "linear");
$('.footer').animate({
bottom: [ "0", "swing" ],
opacity: "1"
}, 1000, "linear");
}
}
你可以保留一個布爾值animationDone
。
在動畫之前將其設置為false,然后為true。 當布爾值為false
時,不要做其他動畫。
你想要鎖定函數調用,鎖應該是一個全局變量並聲明為false:
onScrollMove: function() {
var thisScrol = myScroll.getScrollY()
if (thisScrol < -80 && !locked){
locked = true;
bgfadeToggle('on');
locked = false;
}
if (thisScrol > -80 && !locked){
locked = true;
bgfadeToggle('off');
locked = false;
}
},
您可以使用這樣的延遲調用模式:
onScrollMove: function () {
var thisScrol = myScroll.getScrollY();
scrollCallback.invoke(thisScrol < -80);
};
var scrollCallback = function () {
var _timeoutId,
_delayToCall = 500;
return {
invoke: function (lessThan) {
window.clearTimeout(_timeoutId);
_timeoutId = window.setTimeout(function () {
bgfadeToggle(lessThan ? 'on' : 'off');
}, _delayToCall);
}
};
}();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.