拖拽指令
Vue.directive('drag',//自定义指令
{
bind: function (el, binding) {
let oDiv = el; //当前元素
oDiv.onmousedown = function (e) {
//鼠标按下,计算当前元素距离可视区的距离
let disX = e.clientX - oDiv.offsetLeft;
let disY = e.clientY - oDiv.offsetTop;
document.onmousemove = function (e) {
//通过事件委托,计算移动的距离
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
}
//移动当前元素
oDiv.style.left = l + 'px';
oDiv.style.top = t + 'px';
};
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouseup = null;
};
};
}
}
);
防抖 节流
/**
* 防抖函数:
* 防止抖动,单位时间内事件触发会被重置,避免事件被误伤触发多次。
* 代码实现重在清零 clearTimeout
*/
export function debounce (f, wait = 50) {
clearTimeout(debounceTimer) // 防抖重在清零
debounceTimer = setTimeout(f, wait)
}
/**
* 节流函数:
* 节流:控制流量,单位时间内事件只能触发一次,如果服务器端的限流即 Rate Limit。
* 代码实现重在开锁关锁 timer=timeout; timer=null
*/
export function throttle (f, wait) {
if (throttleTimer) { return }
throttleTimer = setTimeout(() => {
f()
throttleTimer = null // 节流重在开关锁
}, wait)
}