Vue自定义拖动指令v-drag
Vue自定义拖动指令v-drag增加防止点击穿透指令
·
标题Vue自定义拖动指令v-drag
Vue封装自定义全局指令,可以在页面中进行拖动,
- vue自定义全局指令
Vue.directive('drag', {
inserted: function (el) {
let odiv = null, disX, disY
el.addEventListener('mousedown', dragMove)
function dragMove(e) {
odiv = e.currentTarget;
disX = e.clientX - odiv.offsetLeft;
disY = e.clientY - odiv.offsetTop;
document.addEventListener('mousemove', dragDomMove)
document.addEventListener('mouseup', dragDomUp)
}
function dragDomMove(e) {
let left = e.clientX - disX;
let top = e.clientY - disY;
if (left < 0) {
left = 0;
}
if (top < 0) {
top = 0;
}
if (left >= document.documentElement.clientWidth - odiv.offsetWidth) {
left = document.documentElement.clientWidth - odiv.offsetWidth;
}
if (top >= document.documentElement.clientHeight - odiv.offsetHeight) {
top = document.documentElement.clientHeight - odiv.offsetHeight;
}
//移动当前元素
odiv.style.left = left + "px";
odiv.style.top = top + "px";
}
function dragDomUp(e) {
document.removeEventListener('mousemove', dragDomMove)
document.removeEventListener('mouseup', dragDomUp)
}
}
})
防止其他按钮点击进行穿透自定义防止拖动指令
2. 自定义防止拖动指令
Vue.directive('stopdrag', {
inserted: function (el, binding, vnode) {
let element = el;
element.onmousedown = function (e) {
e.stopPropagation()
}
}
})
- 页面中使用
<div class="info" v-drag>
<button v-stopdrag></button>
</div>
更多推荐
已为社区贡献2条内容
所有评论(0)