Vue实现鼠标拖拽元素
实现方法采用Vue自定义指令v-drag拖拽
3642 热度
1214 浏览
如要注册Vue自定义指令,组件中要写入 directives 方法与 methods 同级。
然后再模版中绑定 自定义指令 v-drag
vue
<div v-drag >{{ fromData.text }}</div>
在 directives 方法中定义 drag
javascript
directives: {
drag: function(el) {
let dragBox = el;
dragBox.onmousedown = e => {
//算出鼠标相对元素的位置
let disX = e.clientX - dragBox.offsetLeft;
let disY = e.clientY - dragBox.offsetTop;
document.onmousemove = e => {
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
//移动当前元素
dragBox.style.left = left + "px";
dragBox.style.top = top + "px";
};
document.onmouseup = e => {
//鼠标弹起来的时候不再移动
document.onmousemove = null;
//预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
document.onmouseup = null;
};
};
}
},

声明:Web前端小站 - 前端博客 - 王搏的个人博客|版权所有,违者必究|如未注明,均为原创
转载:转载请注明原文链接 - Vue实现鼠标拖拽元素
评论 (0)
0/50
暂无评论,快来抢沙发吧~