vue自定義指令之拖動頁面的元素


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

源代碼如下:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.outer div{
position:absolute;
width: 100px;
height: 100px;
}
.outer .left{
background-color: red;
top:0;
left:0;
}
.outer .right{
background-color: blue;
top:0;
right:0;
}
</style>
</head>
<body>
<div id="app">
<div class="outer">
<div class="left" v-drag></div>
<div class="right" v-drag></div>
</div>
</div>
<script src="vue.js"></script>
<script>
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'

})
</script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM