vue 实现文本的拖拽_基于Vue实现拖拽效果及阻止拖拽

参考链接中讲的比较详细,我只使用了其中自定义指令的方法。整体代码如下:

data() {return{

}

},

directives: {

drag: {//指令的定义

bind: function(el) {

let oDiv= el; //获取当前元素

oDiv.onmousedown = (e) =>{//算出鼠标相对元素的位置

let disX = e.clientX -oDiv.offsetLeft;

let disY= e.clientY -oDiv.offsetTop;

document.οnmοusemοve= (e) =>{//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置

let left = e.clientX -disX;

let top= e.clientY -disY;

oDiv.style.left= left + 'px';

oDiv.style.top= top + 'px';

};

document.οnmοuseup= (e) =>{

document.οnmοusemοve= null;

document.οnmοuseup= null;

}

}

}

}

}

}

position: absolute;

top:50%;

left:50%;

transform: translate(-50%, -50%);

width: 870px;

height: 510px;

background-color: #3ab5a0;

}

使用方法:在需拖拽功能的元素上添加v-drag启用:

补充:阻止拖拽

上述方法利用自定义指令实现了弹窗的拖拽,补充部分是阻止拖拽,例如:弹窗中有input框,如果想要选中input中的内容就需要阻止弹窗的拖拽

export default {

directives: {

/*自定义拖拽*/

drag: {

inserted: function(el, binding, vnode) {

var odiv = el.parentNode;

odiv.onmousedown = function(eve) {

eve = eve || window.event;

var clientX = eve.clientX;

var clientY = eve.clientY;

var odivX = odiv.offsetLeft;

var odivY = odiv.offsetTop;

var odivLeft = clientX - odivX;

var odivTop = clientY - odivY;

var clientWidth = document.documentElement.clientWidth;

var oWidth = odiv.clientWidth;

var odivRight = clientWidth - oWidth;

var clientHeight = document.documentElement.clientHeight;

var oHeight = odiv.clientHeight;

var odivBottom = clientHeight - oHeight;

document.onmousemove = function(e) {

e.preventDefault();

var left = e.clientX - odivLeft;

if (left < 0) {

left = 0

}

if (left > odivRight) {

left = odivRight

}

var Top = e.clientY - odivTop;

if (Top < 0) {

Top = 0

}

if (Top > odivBottom) {

Top = odivBottom

}

odiv.style.left = left + "px";

odiv.style.top = Top + "px";

}

document.onmouseup = function() {

document.onmouseup = "";

document.onmousemove = "";

}

}

}

},

/*阻止拖拽*/

stopdrag: {

inserted: function(el, binding, vnode) {

let element = el;

element.onmousedown = function(e) {

e.stopPropagation()

}

}

}

}

}

使用方法:在不需拖拽的元素上添加v-stopdrag阻止:


版权声明:本文为weixin_33279929原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。