vue-实现logo移动拖拽并显示区域

<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>
  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值