vue里的自定义指令directives
程序员文章站
2022-05-16 18:35:53
...
在Vue里我们除了可以使用Vue官方给我们定义好的指令外,也可以自己来封装指令。
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.bootcss.com/vue/2.5.17/vue.js"></script>
<style type="text/css">
.drag {
position: absolute;
left: 0px;
top: 0px;
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="root">
<div class="drag" v-drag></div>
<div class="drag" v-drag></div>
<div class="drag" v-drag></div>
</div>
</p>
<script type="text/javascript">
var vm = new Vue({
el: '#root',
data: {
a: 1,
b: 2
},
methods: {
},
directives: {
drag(el){
el.onmousedown = function(e){
// e.pageX 获取鼠标当前位置距离页面的位置。
// el.offsetLeft 获取当前元素距离页面左边的位置
var disx = e.pageX - el.offsetLeft;
var disy = e.pageY - el.offsetTop;
document.onmousemove = function(e) {
el.style.left = e.pageX - disx + 'px';
el.style.top = e.pageY - disy + 'px';
}
document.onmouseup = function(e) {
document.onmousemove = document.onmouseup = null;
}
}
}
}
})
</script>
</body>
</html>
上一篇: 求二叉树度为0,1,2的结点个数
下一篇: Python-获取法定节假日