- 新建drag.js文件
import Vue from 'vue';
const drag = Vue.directive('drag', {
inserted: function(el, data) {
el.onmousedown = function(e) {
if (e.target.id === data.value || !data.value) {
el.style.position = 'absolute'
var disx = e.pageX - el.offsetLeft;
var disy = e.pageY - el.offsetTop;
document.onmousemove = function(e) {
let positionLeft = e.pageX - disx;
let positionTop = e.pageY - disy;
let winWidth = window.innerWidth;
let winHeight = window.innerHeight;;
if (positionLeft <= 0) positionLeft = 0;
if (positionTop <= 0) positionTop = 0;
if (positionLeft > winWidth - el.offsetWidth) positionLeft = winWidth - el.offsetWidth;
if (positionTop > winHeight - el.offsetHeight) positionTop = winHeight - el.offsetHeight;
el.style.left = positionLeft + 'px';
el.style.top = positionTop + 'px';
}
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
}
}
}
}
})
export default drag;
2.main.js引入文件
import drag from './drag.js';
- 使用
<!-- v-drag放到元素上,鼠标按下元素的任何地方都可以拖动 -->
<div class="box" v-drag>
<p id="abc">123456</p>
</div>
<!-- 也可以在后面加上一个子元素的id,以字符串的形式传进去,那样只会按下指定的元素才会拖动 -->
<div class="box" v-drag="'abc'">
<p id="abc">按下</p>
</div>
网友评论