1.页面元素添加,给标签加上指令 v-drag
<div class="drag-w" v-drag >东北大米真好吃,你想吃几碗</div>
2.在ecport default{}中加入如下代码
directives: {
drag (el) {
let oDiv = el // 当前元素
// let self = this // 上下文
oDiv.onclick = function (e) {
if(oDiv.className == 'drag-w'){
oDiv.className = 'drag-d';
return true;
}
oDiv.className = 'drag-w';
}
// 禁止选择网页上的文字
document.onselectstart = function () {
return false
}
oDiv.onmousedown = function (e) {
if(oDiv.className == 'drag-d'){
return true;
}
// 鼠标按下,计算当前元素距离可视区的距离
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
// 移动当前元素
oDiv.style.left = l + 'px'
oDiv.style.top = t + 'px'
}
document.onmouseup = function (e) {
document.onmousemove = null
document.onmouseup = null
}
// return false不加的话可能导致黏连,就是拖到一个地方时div粘在鼠标上不下来,相当于onmouseup失效
return false
}
}
},
3.由于定位方式问题添加css样式
<style lang="css" scoped>
.drag-w{
padding: 5px 10px;
background: rgb(10, 118, 164);
border: 1px solid #3b80b7;
color: rgb(255, 255, 255);
display: inline-block;
position: absolute;
text-align: center;
}
.drag-d{
resize: both;
overflow: auto;
border: 1px solid #980c1c;
padding: 5px 10px;
background: rgb(10, 118, 164);
color: rgb(255, 255, 255);
display: inline-block;
position: absolute;
text-align: center;
}
</style>