<template>
<div class="logo-container">
<img
ref="logo"
src="./wang2.png"
alt="Logo"
class="logo"
@touchstart="onTouchStart"
@touchmove="onTouchMove"
@touchend="onTouchEnd"
:style="{ top: logoPosition.y + 'px', left: logoPosition.x + 'px' }"
/>
</div>
</template>
<script>
export default {
data() {
return {
logoPosition: {
x: window.innerWidth - 200,
y: window.innerHeight - 200,
},
isDragging: false,
initialTouchPos: { x: 0, y: 0 },
};
},
mounted() {
this.adjustLogoPosition(); // 在组件挂载时调整 logo 位置
window.addEventListener('resize', this.adjustLogoPosition); // 在窗口大小改变时调整 logo 位置
},
beforeDestroy() {
window.removeEventListener('resize', this.adjustLogoPosition); // 在组件销毁前移除事件监听
},
methods: {
adjustLogoPosition() {
this.logoPosition.x = window.innerWidth - 200;
console.log('with'+window.innerWidth);
this.logoPosition.y = window.innerHeight - 200 - document.querySelector(".navbar").clientHeight;
console.log('heigh'+window.innerHeight);
console.log('bar'+document.querySelector(".navbar").clientHeight)
},
onTouchStart(event) {
this.isDragging = true;
const touch = event.touches[0];
this.initialTouchPos.x = touch.clientX - this.logoPosition.x;
this.initialTouchPos.y = touch.clientY - this.logoPosition.y;
},
onTouchMove(event) {
if (this.isDragging) {
event.preventDefault();
const touch = event.touches[0];
// 计算新的 logo 位置
const newX = touch.clientX - this.initialTouchPos.x;
const newY = touch.clientY - this.initialTouchPos.y;
// 确保 logo 不超出屏幕边界
this.logoPosition.x = Math.max(0, Math.min(newX, window.innerWidth - this.$refs.logo.clientWidth));
this.logoPosition.y = Math.max(0, Math.min(newY, window.innerHeight - this.$refs.logo.clientHeight - document.querySelector(".navbar").clientHeight));
}
},
onTouchEnd() {
this.isDragging = false;
},
},
};
</script>
<style>
.logo-container {
position: relative;
}
.logo {
position: absolute;
cursor: pointer;
/* 其他样式可以根据需要进行调整 */
width: 200px;
height: 200px;
}
</style>
vue-实现logo移动拖拽并显示区域
最新推荐文章于 2024-05-10 15:59:47 发布