Vue+js 给按钮增加拖动手势事件

给自定义图片、按钮增加手势拖动,并增加弹性效果

html

目录

js

data() {
    return {
            leftX: 0,
            topY: 0,
            startX: '',
            startY: '',
            alphaValue: '0.5',
            maxX: 0,
            maxH: 0
    }
},
methods: {
        touchStart(event) {
            this.leftX = event.targetTouches[0].pageX - this.startX;
            this.maxX = document.body.clientWidth
            this.maxH = document.body.clientHeight
            this.alphaValue = '1'
            document.body.style.overflow = 'hidden'
            this.startX = event.targetTouches[0].pageX - this.$refs.matrix_box.offsetLeft;
            this.startY = event.targetTouches[0].pageY - this.$refs.matrix_box.offsetTop;
        },
        touchMove(event) {
            this.alphaValue = '1'
            event.stopPropagation()
            this.leftX = event.targetTouches[0].pageX - this.startX;
            this.topY = event.targetTouches[0].pageY - this.startY;
            this.$refs.matrix_box.style.position = 'absolute'
            this.$refs.matrix_box.style.left = this.leftX + "px";
            this.$refs.matrix_box.style.top = this.topY + "px";
        },
        touchend(event) {
            // 根据自己设备宽高计算拖动范围
            if(this.leftX < 0 || this.leftX < (this.maxX - 40)/2) {
                this.leftX = 0
            }else if(this.leftX > (this.maxX - 40)/2) {
                this.leftX = this.maxX - 40
            }
            if(this.topY < -290) {
                this.topY = -290
            }else if(this.topY > (this.maxH - 75 - 310)) {
                this.topY = this.maxH - 75 - 310
            }

            this.$refs.matrix_box.style.position = 'absolute'
            this.$refs.matrix_box.style.left = this.leftX + "px";
            this.$refs.matrix_box.style.top = this.topY + "px";
            document.body.style.overflow = ''
            this.$refs.matrix_box.removeEventListener("touchstart", this.touchStart)
            document.removeEventListener("touchmove", this.touchMove )
            setTimeout(() => {
                this.alphaValue = '0.5'
            }, 1000);
        },
}
       

你可能感兴趣的:(Vue+js 给按钮增加拖动手势事件)