Vue实现拖放功能
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue实现拖放功能</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style>
        *{margin:0;padding: 0}
        .box{
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="box" v-drag="flag"></div>
    </div>
    <div data-id="0"  id="box"></div>
</body>
</html>

<script>
    Vue.directive("drag",(el,{modifiers,value})=>{
        el.style.position = "absolute";
        let {x,y} = modifiers;
       

        el.addEventListener("mousedown",donw);
        
        var disX,disY;
        function donw(e){
            disX = e.offsetX;
            disY = e.offsetY;
            document.addEventListener("mousemove",move);
            document.addEventListener("mouseup",up)


        }

        function move(e){
           var l = e.clientX - disX;
           var t = e.clientY - disY;


            if(value){

                if(x){
                    el.style.left = l + 'px';
                }
                if(y){
                    el.style.top = t + 'px';
                }
                
                if(x&&y || (!x&&!y)){
                    el.style.left = l + 'px';
                    el.style.top = t + 'px';
                }
                 
            }
           
        }

        function up(e){
            document.removeEventListener("mousemove",move);
            document.removeEventListener("mouseup",up);
        }
    })



    new Vue({
        el:"#app",
        data:{
            flag:true,
            msg:"123"
        }
    })
</script>
posted on 2021-01-28 14:24  js攻城狮  阅读(99)  评论(0编辑  收藏  举报