<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
<div id="drag" v-drag="{callback:demo,data:msg}"></div>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
msg: '我是参数',
}
},
// 自定义指令
directives:{
// 元素拖动
drag: {
// 指令的定义
bind(el, binding) { // el 为绑定元素, binding 为绑定给指令的对象
let item = binding.value.item;
let callback = binding.value.callback;
if(typeof callback === 'undefined' || typeof callback !== 'undefined' && typeof item !== 'undefined' && typeof item.param.position === 'undefined'){
return false;
}
el.onmousedown = (elem) => {
elem.preventDefault()
elem.stopPropagation();
//鼠标按下,计算当前元素距离可视区的距离
let disX = elem.clientX - el.offsetLeft;
let disY = elem.clientY - el.offsetTop;
document.onmousemove = (docElem)=>{
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = docElem.clientX - disX;
let top = docElem.clientY - disY;
if(typeof item !== 'undefined'){
callback({item:item,position:{top:top,left:left}})
}else{
callback({position:{top:top,left:left}})
}
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
return false;
};
}
}
},
methods: {
demo(data) {
console.log(data)
},
}
})
</script>
</body>
<style>
#drag{
width:100px;
height:100px;
background:blue;
overflow:hidden;
}
</style>
</html>
本资源由随笔博客发布。发布者:五维国度,转载请注明出处:http://blog.suibi.site/archives/4322
本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。