美文网首页
vue自定义指令之拖拽指令

vue自定义指令之拖拽指令

作者: jw_fc89 | 来源:发表于2020-07-25 17:17 被阅读0次

    定义的全局指令:
    使用方式

    <!-- 变成了一个可以被拖拽的元素 啦啦啦 -->
    <div v-drag></div> 
    
    import Vue from "vue"
    
    Vue.directive("drag", {
        bind(el) {
            el.onmousedown = function (event) {
                var event = event || window.event;  //兼容IE浏览器
                //    鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
                var diffX = event.clientX - el.offsetLeft;
                var diffY = event.clientY - el.offsetTop;
                if (typeof el.setCapture !== 'undefined') {
                    el.setCapture();
                }
                document.onmousemove = function (event) {
                    var event = event || window.event;
                    var moveX = event.clientX - diffX;
                    var moveY = event.clientY - diffY;
                    if (moveX < 0) {
                        moveX = 0
                    } else if (moveX > window.innerWidth - el.offsetWidth) {
                        moveX = window.innerWidth - el.offsetWidth
                    }
                    if (moveY < 0) {
                        moveY = 0
                    } else if (moveY > window.innerHeight - el.offsetHeight) {
                        moveY = window.innerHeight - el.offsetHeight
                    }
                    el.style.left = moveX + 'px';
                    el.style.top = moveY + 'px'
                }
                document.onmouseup = function (event) {
                    this.onmousemove = null;
                    this.onmouseup = null;
                    //修复低版本ie bug  
                    if (typeof el.releaseCapture != 'undefined') {
                        el.releaseCapture();
                    }
                }
            }
        }
    })
    

    相关文章

      网友评论

          本文标题:vue自定义指令之拖拽指令

          本文链接:https://www.haomeiwen.com/subject/ngdmlktx.html