Vue自定义指令v-drag实现简单的拖拽效果

责编:menVScode 2020-10-13 13:33 阅读(53)

自定义指令v-drag 

(1)l 存在时 只能横向拖拽;

(2)t 存在时 只能纵向拖拽;

(3)l、t都存在时 可以任意方向拖拽;

代码如下:

<!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>拖拽</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #box{
            background: red;
            width: 100px;
            height: 100px;
            position: absolute;
 
        }
    </style>
    <script src="vue.js"></script>
</head>
<body>
    <div id="app">
        <div id="box" v-drag.l.t="flag"></div>
    </div>
    <script>
        Vue.directive("drag",(el,{modifiers,value})=>{
            let{l,t}=modifiers;
 
 
            el.addEventListener("mousedown",handleDownCb)
 
            let disX,disY;
            function handleDownCb(e){
                disX=e.offsetX;
                disY=e.offsetY;
                // console.log(disX,disY)
                document.addEventListener("mousemove",handleMoveCb);
                document.addEventListener("mouseup",handleUpCb);
            }
 
            function handleMoveCb(e){
                let x=e.clientX-disX;
                let y=e.clientY-disY;
                if((l&&t) && value){
                    el.style.left=x+"px";                    
                    el.style.top=y+"px";
                    return;
                }
 
                if(l&&value){
                    el.style.left=x+"px";                    
                    return;
                }
                if(t&&value){
                    el.style.top=y+"px";
                    return;
                }
            }
 
            function handleUpCb(){
                document.removeEventListener("mousemove",handleMoveCb);
                document.removeEventListener("mouseup",handleUpCb);
            }
 
        })
        let vm=new Vue({
            el:"#app",
            data:{
                flag:true
            }
        })
    </script>
</body>
</html>

注:

改变v-drag.l、v-drag.t、v-drag.l.t分别可实现横向、纵向、任意方向的拖拽。

原址:https://blog.csdn.net/qq_45092792/article/details/97130208

标签: 拖拽 vue
前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码