自学内容网 自学内容网

vue2单个图片可以任意拖动

在这里插入图片描述

<template>
  <div>
    <el-badge
      :value="9"
      class="item"
      :max="99"
      :style="ballStyle2">
      <div class="drag-ball" :style="ballStyle" @mousedown="handleMouseDown" />
    </el-badge>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isDraggingType :'',
      isDragging: false,
      ballPosition: { x: 50, y: 200 }, // 拖拽div初始位置
      startPosition: { x: 0, y: 0 }, // 鼠标按下时的位置
    }
  },
  computed: {
    ballStyle() {
      return {
        position: 'fixed',
        right: `${ this.ballPosition.x }px`,
        bottom: `${ this.ballPosition.y }px`,
      }
    },
    ballStyle2() {
      return {
        position: 'fixed',
        right: `${ this.ballPosition.x }px`,
        bottom: `${ this.ballPosition.y + 50 }px`,
      }
    },
  },
  methods: {
    handleMouseDown(event) {
      this.isDragging = true
      this.startPosition = { x: event.clientX, y: event.clientY }
      document.addEventListener('mousemove', this.handleMouseMove)
      document.addEventListener('mouseup', this.handleMouseUp)
    },
    handleMouseMove(event) {
      if (this.isDragging) {
        const diffX = event.clientX - this.startPosition.x
        const diffY = event.clientY - this.startPosition.y
        if (diffX > 5 || diffY > 5) { // 判断点击与拖动的区别
          this.isDraggingType = 'dragging'
        }else{
          this.isDraggingType = ''
        }
        this.ballPosition = {
          x: this.ballPosition.x - diffX,
          y: this.ballPosition.y - diffY,
        }
        this.startPosition = { x: event.clientX, y: event.clientY }
        this.constrainToScreen()
      }
    },
    handleMouseUp() {
      this.isDragging = false
      document.removeEventListener('mousemove', this.handleMouseMove)
      document.removeEventListener('mouseup', this.handleMouseUp)
    },
    constrainToScreen() {
      // 限制拖拽时在屏幕范围内
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight
      const ballRadius = 50 // 假设悬浮球半径为50px
      if (this.ballPosition.x < ballRadius) {
        this.ballPosition.x = ballRadius
      } else if (this.ballPosition.x > windowWidth - ballRadius - 190) {
        this.ballPosition.x = windowWidth - ballRadius - 190
      }
      if (this.ballPosition.y < ballRadius) {
        this.ballPosition.y = ballRadius
      } else if (this.ballPosition.y > windowHeight - ballRadius - 100) {
        this.ballPosition.y = windowHeight - ballRadius - 100
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.drag-ball {
  cursor: move;
  width: 50px;
  height: 50px;
  background-image: url('~@/assets/intelligentCustomer/microbot.png');
  background-size: contain;
  background-repeat: repeat;
  z-index: 19;
}
</style>

原文地址:https://blog.csdn.net/csstmg/article/details/140271559

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!