练习内容 => 拖动页面中的元素
onmouseover => 鼠标经过
onmouseout => 鼠标离开
onmousedown =>鼠标按下
onmousemove =>鼠标按下拖动
onmouseup => 鼠标松开
1、在页面上放两个div,并添加各自的样式
<div id="itany">
<div class="hello" v-drag>zhang</div>
<div class="world" v-drag>cheng</div>
</div>
<style>
#itany div {
width: 100px;
height: 100px;
position: absolute;
}
#itany .hello {
background-color: red;
top: 0;
left: 0;
}
#itany .world {
background-color: blue;
top: 0;
right: 0;
}
</style>
2、写vue实例
var vm = new Vue({
el: '#itany',
data: {
msg: 'hello',
},
}
});
3、注册拖拽指令drag
Vue.directive('drag', function(el) {
el.onmousedown = function(e) {
//获取鼠标点击处分别与div左边和上边的距离:鼠标位置-div位置
var disX = e.clientX - el.offsetLeft;
var disY = e.clientY - el.offsetTop;
// console.log(disX,disY);
//包含在onmousedown里面,表示点击后才移动,为防止鼠标移出div,使用document.onmousemove
document.onmousemove = function(e) {
//获取移动后div的位置:鼠标位置-disX/disY
var l = e.clientX - disX;
var t = e.clientY - disY;
el.style.left = l + 'px';
el.style.top = t + 'px';
}
//停止移动
document.onmouseup = function(e) {
document.onmousemove = null;
document.onmouseup = null;
}
}
});
网友评论