項目常用代碼

節(jié)流

export function throttle(fn, time, immediate= true) {
let timer,
    immediateStart = immediate;
return function() {
    if (immediateStart) {
        db.apply(this, arguments);
        immediateStart = false;
    }
    if (!timer) {
        timer = setTimeout(() => {
            fn.apply(this, arguments);
            timer = null;
        }, time);
    }
};

}

防抖

   export function debounce(db, time, immediate = true) {
let timer,
    immediateStart = immediate;
return function() {
    if (immediateStart) {
        db.apply(this, arguments);
        immediateStart = false;
    }
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
        immediateStart = true;
    }, time);
};

}

頁面滾動(requestAnimationFrame)

  /**
 *
 * @param {number} top 跳轉(zhuǎn)位置
 * @param {number} frameNum 跑多少幀,默認20
 * @returns
 */
export function toScrollTop(top, frameNum = 20) {
if (isNaN(frameNum) || isNaN(frameNum)) return;
if (top < 0) top = 0;

let documentElement = document.documentElement;
let currentScrollTop = documentElement.scrollTop;

const distance = Math.abs(currentScrollTop - top);
if (distance < frameNum) {
    //滾動距離小于幀數(shù),直接滾動并跳出。
    documentElement.scrollTop = top;
    return;
}
//每次滾動距離
const everyDistance = distance / frameNum;
//是否向下滾動
const isDown = currentScrollTop - top < 0;
const rAF = window.requestAnimationFrame || ((func) => setTimeout(func, 16));

const frameFunc = () => {
    if (isDown) {
        if (currentScrollTop < top) {
            documentElement.scrollTop = currentScrollTop += everyDistance;
            rAF(frameFunc);
            return;
        }
    } else {
        if (currentScrollTop > top) {
            documentElement.scrollTop = currentScrollTop -= everyDistance;
            rAF(frameFunc);
            return;
        }
    }
    documentElement.scrollTop = top;
};
rAF(frameFunc);
}

vue全局點擊防抖

  /**
 * 全局點擊防抖
   */
  const on = Vue.prototype.$on;
  Vue.prototype.$on = function(event, func) {
let timer;
let flag = true;
let newFunc = func;
if (event == "click") {
    newFunc = function() {
        if (flag) {
            func.apply(this, arguments);
            flag = false;
        }
        if (timer) clearTimeout(timer);
        timer = setTimeout(function() {
            flag = true;
        }, 500);
    };
}
    on.call(this, event, newFunc);
  };
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容