1. 程式人生 > 其它 >實現vue中拖拽

實現vue中拖拽

技術標籤:vue.js

<div class="Slider" v-drag>

v-drag是自定義指令

directives: {
       drag: {
            // 指令的定義
           bind: function (el) {
                   let odiv = el;   //獲取當前元素
           el.onmousedown = (e) => {
                    //算出滑鼠相對元素的位置
           let disX = e.clientX -
odiv.offsetLeft; let disY = e.clientY - odiv.offsetTop; let left = ''; let top = ''; document.onmousemove = (e)=>{ //用滑鼠的位置減去滑鼠相對元素的位置,得到元素的位置 left = e.clientX -
disX; top = e.clientY - disY; //繫結元素位置到positionX和positionY上面 //移動當前元素 odiv.style.left = left + 'px'; odiv.style.top = top + 'px'; }; document.
onmouseup = (e) => { document.onmousemove = null; document.onmouseup = null; }; }; } } }