节流
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 跳转位置
* @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) {
//滚动距离小于帧数,直接滚动并跳出。
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);
};