Vue案例之拖拽

Vue拖拽

clipboard.png

<div id="box">                                                       HTML
    位置
    <br>x:{{val.x}} <br>y:{{val.y}}
    <div v-drag="greet" id="drag" :style="style">
    //注意這裏要經過指令綁定函數將當前元素的位置數據傳出來
    </div>
</div>
Vue.directive('drag',//自定義指令                                      JS
        {bind:function (el, binding) {
                let oDiv = el;   //當前元素
                let self = this;  //上下文
                oDiv.onmousedown = function (e) {
                 //鼠標按下,計算當前元素距離可視區的距離
                    let disX = e.clientX - oDiv.offsetLeft;
                    let disY = e.clientY - oDiv.offsetTop;

                    document.onmousemove = function (e) {
                      //經過事件委託,計算移動的距離 
                        let l = e.clientX - disX;
                        let t = e.clientY - disY;
                      //移動當前元素  
                        oDiv.style.left = l + 'px';
                        oDiv.style.top = t + 'px';
                         //將此時的位置傳出去
                        binding.value({x:e.pageX,y:e.pageY})
                    };
                    document.onmouseup = function (e) {
                    
                        document.onmousemove = null;
                        document.onmouseup = null;
                     };
                };
            }
        }
    );
    window.onload = function () {
        let vm = new Vue({
            el: '#box',
            data: {
                val: '123',
                style: {
                    width: '100px',
                    height: '100px',
                    background: 'aqua',
                    position: 'absolute',
                    right: '30px',
                    top: 0
                }
            },
            methods:{
            //接受傳來的位置數據,並將數據綁定給data下的val
                greet(val){
                    vm.val = val;
                }
            } ,
      });
    }
相關文章
相關標籤/搜索