<template>
  <div
    ref="parent"
    class="parent-container"
  >
    <div class="draggable-box" />
  </div>
</template>
<script>
export default {
  mounted() {
    // 获取父级容器
    const parent = this.$refs.parent;

    // 获取拖动的元素
    const box = this.$el.querySelector('.draggable-box');

    // 定义拖动的初始位置和鼠标位置
    let startX, startY, initialMouseX, initialMouseY;

    // 绑定鼠标按下事件
    box.addEventListener('mousedown', function(event) {
      startX = box.offsetLeft;
      startY = box.offsetTop;
      initialMouseX = event.clientX;
      initialMouseY = event.clientY;

      // 绑定鼠标移动事件
      document.addEventListener('mousemove', dragBox);

      // 绑定鼠标抬起事件
      document.addEventListener('mouseup', stopDraggingBox);
    });

    // 拖动函数
    function dragBox(event) {
      const currentMouseX = event.clientX;
      const currentMouseY = event.clientY;

      const diffX = currentMouseX - initialMouseX;
      const diffY = currentMouseY - initialMouseY;

      // 计算元素的新位置
      const newBoxLeft = startX + diffX;
      const newBoxTop = startY + diffY;

      // 判断是否超出父级容器的范围
      if (newBoxLeft >= 0 && newBoxLeft + box.offsetWidth <= parent.offsetWidth) {
        box.style.left = newBoxLeft + 'px';
      }
      if (newBoxTop >= 0 && newBoxTop + box.offsetHeight <= parent.offsetHeight) {
        box.style.top = newBoxTop + 'px';
      }
    }

    // 停止拖动函数
    function stopDraggingBox() {
      document.removeEventListener('mousemove', dragBox);
      document.removeEventListener('mouseup', stopDraggingBox);
    }

    // 绑定缩放事件
    box.addEventListener('wheel', function(event) {
      event.preventDefault();

      const scale = event.deltaY > 0 ? 0.9 : 1.1;

      box.style.width = box.offsetWidth * scale + 'px';
      box.style.height = box.offsetHeight * scale + 'px';

      // 判断是否超出父级容器的范围
      if (box.offsetLeft + box.offsetWidth > parent.offsetWidth) {
        box.style.width = parent.offsetWidth - box.offsetLeft + 'px';
      }
      if (box.offsetTop + box.offsetHeight > parent.offsetHeight) {
        box.style.height = parent.offsetHeight - box.offsetTop + 'px';
      }
    });
  },
};
</script>
<style lang="scss" scoped>
.parent-container {
  width: 500px;
  height: 500px;
  position: relative;
}

.draggable-box {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
}
</style>
