拖拽指令
Vue.directive('drag',//自定義指令
{
bind: function (el, binding) {
let oDiv = el; //當(dāng)前元素
oDiv.onmousedown = function (e) {
//鼠標(biāo)按下,計(jì)算當(dāng)前元素距離可視區(qū)的距離
let disX = e.clientX - oDiv.offsetLeft;
let disY = e.clientY - oDiv.offsetTop;
document.onmousemove = function (e) {
//通過(guò)事件委托舞萄,計(jì)算移動(dòng)的距離
let l = e.clientX - disX;
let t = e.clientY - disY;
// 防止越界
if (l < 0) {
l = 0
}
if (l > document.documentElement.clientWidth - oDiv.getBoundingClientRect().width) {
l = document.documentElement.clientWidth - oDiv.getBoundingClientRect().width
}
if (t < 0) {
t = 0
}
if (t > document.body.clientHeight - oDiv.getBoundingClientRect().height) {
t = document.body.clientHeight - oDiv.getBoundingClientRect().height - 40
}
//移動(dòng)當(dāng)前元素
oDiv.style.left = l + 'px';
oDiv.style.top = t + 'px';
};
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouseup = null;
};
};
}
}
);
防抖 節(jié)流
/**
* 防抖函數(shù):
* 防止抖動(dòng)蹂析,單位時(shí)間內(nèi)事件觸發(fā)會(huì)被重置渐白,避免事件被誤傷觸發(fā)多次。
* 代碼實(shí)現(xiàn)重在清零 clearTimeout
*/
export function debounce (f, wait = 50) {
clearTimeout(debounceTimer) // 防抖重在清零
debounceTimer = setTimeout(f, wait)
}
/**
* 節(jié)流函數(shù):
* 節(jié)流:控制流量粪狼,單位時(shí)間內(nèi)事件只能觸發(fā)一次退腥,如果服務(wù)器端的限流即 Rate Limit任岸。
* 代碼實(shí)現(xiàn)重在開(kāi)鎖關(guān)鎖 timer=timeout; timer=null
*/
export function throttle (f, wait) {
if (throttleTimer) { return }
throttleTimer = setTimeout(() => {
f()
throttleTimer = null // 節(jié)流重在開(kāi)關(guān)鎖
}, wait)
}