vue2中实现一个可移动的弹框

先创建一个可拖拽的外壳

 mounted() {
        this.theDrag();
    },
methods: {
       //拖拽
        theDrag() {
            //创建容器
            let container = window.document.body;
            //将创建的div添加到容器中
            container.appendChild(window.document.getElementById("theDrag"));

            //获取到box
            let box = window.document.getElementById("theDrag");

            //为box绑定一个鼠标按下事件
            box.onmousedown = function (event) {
                event = event || window.event;//解决浏览器兼容问题

                //div的左偏移量=鼠标.clientX-元素.ofsetLeft
                let boxLeft = event.clientX - box.offsetLeft;

                //div的上偏移量=鼠标.clientY-元素.ofsetTop
                let boxTop = event.clientY - box.offsetTop;

                //为document绑定一个onmousemove事件
                document.onmousemove = function (event) {
                    event = event || window.event;//解决浏览器兼容问题

                    //获取鼠标的坐标
                    let left = event.clientX - boxLeft;
                    let top = event.clientY - boxTop;

                    //盒子移动的最大偏移量=浏览器宽度-盒子宽度
                    let moveLeft = document.documentElement.clientWidth - box.offsetWidth;
                    let moveTop = document.documentElement.clientHeight - box.offsetHeight;

                    //让盒子不超出浏览器范围
                    if (left <= 0) {
                        left = 0;
                    }
                    else if (left > moveLeft) {
                        left = moveLeft;
                    }
                    else {
                        box.style.left = left + "px";
                    }

                    if (top <= 0) {
                        top = 0;
                    }
                    else if (top > moveTop) {
                        top = moveTop;
                    }
                    else {
                        box.style.top = top + "px";
                    }

                };

                //为document绑定一个鼠标抬起事件,鼠标松开时,将box固定在当前位置
                document.onmouseup = function () {
                    //取消document的onmousemove事件
                    document.onmousemove = null;

                    //取消document的onmouseup事件
                    document.onmouseup = null;
                };
            }
        },
}
``

###页面创建弹框


你可能感兴趣的:(vue2中实现一个可移动的弹框)