html
<template>
<div>
<div
:style="{ top: top + 'px', left: left + 'px' }"
ref="move_div"
@touchstart="down"
@touchmove="move"
@touchend="end"
class="back"
@click="handleBack"
>
<van-image :src="require('@/assets/imgs/commom/back.png')"></van-image>
</div>
</div>
</template>
js
export default class DefaultLayout extends Vue {
$refs!: {
move_div: HTMLDivElement;
};
flags = false;
position = { x: 0, y: 0, left: 0, top: 0 };
width = window.innerWidth;
height = window.innerHeight;
top = 0;
left = 0;
mounted() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.top = this.height - 80 - 60;
this.left = this.width - 80;
}
down(event: any) {
this.flags = true;
const refs = this.$refs.move_div.getBoundingClientRect();
let touch = event;
if (event.touches) {
touch = event.touches[0];
console.log(touch, "touch");
}
this.position.x = touch.clientX;
this.position.y = touch.clientY;
this.position.left = refs.left;
this.position.top = refs.top;
}
move(event: any) {
if (this.flags) {
let touch = event;
if (event.touches) {
touch = event.touches[0];
}
const xPum = this.position.left + touch.clientX - this.position.x;
const yPum = this.position.top + touch.clientY - this.position.y;
this.left = xPum;
this.top = yPum;
this.banOut();
document.addEventListener(
"touchmove",
function() {
event.preventDefault();
},
{ passive: false },
);
}
}
end() {
this.flags = false;
this.banOut();
}
banOut() {
const refs = this.$refs.move_div.getBoundingClientRect();
if (this.left < 0) {
this.left = 0;
} else if (this.left > this.width - refs.width) {
this.left = this.width - refs.width;
}
if (this.top < 0) {
this.top = 0;
} else if (this.top > this.height - refs.height) {
this.top = this.height - refs.height;
}
}
}
css
<style scoped>
.back {
width: 80px;
height: 80px;
position: absolute;
top: 0;
left: 0;
z-index: 9999;
}
</style>