Vue自定义指令 元素拖拽移动

Vue3 自定义指令 元素拖拽移动

Vue.directive('drag', {
            mounted(el: HTMLElement, binding) {
                let offsetX: number, offsetY: number,
                    clientX: number, clientY: number,
                    windowWidth: number, windowHeight: number,
                    criticalX: number, criticalY: number,
                    padding = 20;
                windowWidth = window.innerWidth;
                windowHeight = window.innerHeight;

                function move(event: MouseEvent) {
                    el.style.cursor = 'move'
                    offsetX = el.offsetLeft
                    offsetY = el.offsetTop
                    criticalX = windowWidth - offsetX - el.clientWidth
                    criticalY = windowHeight - offsetY - el.clientHeight
                    if ((offsetX > padding || event.movementX > 0) && (criticalX >= padding || (criticalX <= padding && event.movementX < 0))) {
                        el.style.left = offsetX + event.movementX + 'px'
                    }
                    if ((offsetY > padding || event.movementY > 0) && (criticalY >= padding || (criticalY <= padding && event.movementY < 0))) {
                        el.style.top = offsetY + event.movementY + 'px'
                    }
                }

                function destroy() {
                    el.removeEventListener("mousemove", move)
                    el.style.cursor = 'default'
                    window.removeEventListener("mouseup", destroy)
                }


                el.addEventListener("mousedown", function (event) {
                    clientX = event.clientX
                    clientY = event.clientY
                    el.addEventListener('mousemove', move)
                    window.addEventListener("mouseup", destroy)
                    el.addEventListener("mouseup", destroy)
                })
            }
        })

你可能感兴趣的:(vue.js,javascript,前端,vue)