1.html

<div id="app1">
     <div v-drag class="drag"></div>
     <div v-drag class="drag"></div>
</div>

2.CSS

.drag{
            width: 100px;
            height: 100px;
            position: absolute;
            top: 0;
            left: 0;
            background-color: red;
}

3.js

// 拖动div元素
    let vm1 = new Vue({
        el:'#app1',
        // 自定义指令
        directives:{
            drag(el,bindings){
                el.onmousedown = function(e){
                    var disx = e.pageX - el.offsetLeft;
                    var disy = e.pageY - el.offsetTop;
                    document.onmousemove = function (e){
                        el.style.left = e.pageX - disx+'px';
                        el.style.top = e.pageY - disx+'px';
                    }
                    document.onmouseup = function(){
                        document.onmousemove = document.onmouseup = null;
                    }
                }
            }
        }
    })

 

Logo

前往低代码交流专区

更多推荐