1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > html怎么移动到vue vue自定义指令之拖动页面的元素

html怎么移动到vue vue自定义指令之拖动页面的元素

时间:2022-01-12 03:18:38

相关推荐

html怎么移动到vue vue自定义指令之拖动页面的元素

此案例中,用到了鼠标事件onmousedown、onmousemove、onmouseup

源代码如下:

Document

.outer div{

position:absolute;

100px;

height: 100px;

}

.outer .left{

background-color: red;

top:0;

left:0;

}

.outer .right{

background-color: blue;

top:0;

right:0;

}

Vue.directive('drag',function(el){

el.onmousedown = function(e){

//获取鼠标点击处分别与div左边和上边的距离:鼠标位置-div位置

var divx = e.clientX - el.offsetLeft;

var divy = e.clientY - el.offsetTop;

//包含在onmousedown里,表示点击后才移动,为防止鼠标移出div,使用document.onmousemove

document.onmousemove = function(e){

//获取移动后div的位置:鼠标位置-divx/divy

var l = e.clientX - divx;

var t = e.clientY - divy;

el.style.left=l+'px';

el.style.top=t+'px';

}

document.onmouseup = function(e){

document.onmousemove = null;

document.onmouseup = null;

}

}

})

var vm = new Vue({

el:'#app'

})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。