touch.vue
<template>
<transition>
<div
ref="breathing_lamp"
class="breathing_lamp"
@click="onclick()"
@touchstart.stop="handleTouchStart"
@touchmove.prevent.stop="handleTouchMove($event)"
@touchend.stop="handleTouchEnd"
:style="{
left: left + 'px',
top: top + 'px',
width: itemWidth + 'px',
height: itemHeight + 'px',
}"
v-text="text"
v-if="isShow"
>
{{ text }}
</div>
</transition>
</template>
<script>
export default {
props: {
text: {
type: String,
default: "ball",
},
itemWidth: {
type: Number,
default: 50,
},
itemHeight: {
type: Number,
default: 50,
},
},
data() {
return {
left: 0,
top: 0,
startToMove: false,
isShow: true,
timer: null,
currentTop: null,
clientW: document.documentElement.clientWidth,
clientH: document.documentElement.clientHeight,
};
},
created() {
this.left = this.clientW - this.itemWidth - 30;
this.top = this.clientH / 2 - this.itemHeight / 2;
},
methods: {
onclick() {
console.log("I am a small clouds");
},
handleTouchStart() {
this.startToMove = true;
this.$refs.breathing_lamp.style.transition = "none";
},
handleTouchMove(e) {
const clientX = e.targetTouches[0].clientX;
const clientY = e.targetTouches[0].clientY;
const isInScreen =
clientX <= this.clientW &&
clientX >= 0 &&
clientY <= this.clientH &&
clientY >= 0;
if (this.startToMove && e.targetTouches.length === 1) {
if (isInScreen) {
this.left = clientX - this.itemWidth / 2;
this.top = clientY - this.itemHeight / 2;
}
}
},
handleTouchEnd() {
if (this.left < this.clientW / 2) {
this.left = 30;
this.handleIconY();
} else {
this.left = this.clientW - this.itemWidth - 30;
this.handleIconY();
}
this.$refs.breathing_lamp.style.transition = "all .3s";
},
handleIconY() {
if (this.top < 0) {
this.top = 30;
} else if (this.top + this.itemHeight > this.clientH) {
this.top = this.clientH - this.itemHeight - 30;
}
},
},
};
</script>
<style>
.breathing_lamp {
position: fixed;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: orange;
line-height: 50px;
text-align: center;
color: #fff;
}
</style>
然后在需要的把这个文件以组件的形式来进行引入就可
|