全局自定义拖拽vue

 1/在根目录创建一个tz.js

export default {
    inserted(el) {
        let switchPos = {
            x: 10,
            y: 85,
            startX: 0,
            startY: 0,
            endX: 0,
            endY: 0
        }
        el.addEventListener('touchstart', function (e) {
            console.log(e)
            switchPos.startX = e.touches[0].pageX
            switchPos.startY = e.touches[0].pageY
        })
        el.addEventListener('touchend', function (e) {
            switchPos.x = switchPos.endX
            switchPos.y = switchPos.endY
            switchPos.startX = 0
            switchPos.startY = 0
        })
        el.addEventListener('touchmove', function (e) {
            if (e.touches.length > 0) {
                let offsetX = e.touches[0].pageX - switchPos.startX
                let offsetY = e.touches[0].pageY - switchPos.startY
                let x = switchPos.x - offsetX
                let y = switchPos.y - offsetY
                if (x + el.offsetWidth > document.documentElement.offsetWidth) {
                    x = document.documentElement.offsetWidth - el.offsetWidth
                }
                if (y + el.offsetHeight > document.documentElement.offsetHeight) {
                    y = document.documentElement.offsetHeight - el.offsetHeight
                }
                if (x < 0) {
                    x = 0
                }
                if (y < 0) {
                    y = 0
                }
                el.style.right = x + 'px'
                el.style.bottom = y + 'px'
                switchPos.endX = x
                switchPos.endY = y
                e.preventDefault()
            }
        })
    }
}

2/在main.js中引入

// 拖拽全局引入

import tz from "../tz"

//全局自定义指令。第一个参数是名字,第二个是引入的拖拽.js名字

Vue.directive('xin',tz)

 3/在app.vue中给要加拖拽的盒子标签加上v-名字,这里就是v-xin





效果就是下面的蓝色小信封:

全局自定义拖拽vue_第1张图片

 

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