vue 原生js拖拽demo

前言

原生js事件实现拖拽

 实例

<template>
  <div class="drag-content" ref="dragContent">
    <div class="div-drag" @mousedown="tagDraggable($event)"></div>
  </div>
</template>
<script>
export default {
  name: '',
  data () {
    return {

    }
  },
  components: {},
  props: {},
  computed: {},
  methods: {
    // 标签拖拽
    tagDraggable (e) {
      // 获取目标元素
      e = e || window.event
      let odiv = e.target;
      if (!odiv.className.includes('div-drag')) return
      // 算出鼠标相对元素的位置
      let disX = e.clientX - odiv.offsetLeft;
      let disY = e.clientY - odiv.offsetTop;
      if (e.preventDefault) {
        e.preventDefault()
      } else {
        e.returnValue = false
      }
      document.onmousemove = (e) => {    //鼠标按下并移动的事件
        // 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
        e = e || window.event
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        let width = this.$refs.dragContent.offsetWidth
        let height = this.$refs.dragContent.offsetHeight
        // 标签不能移动到容器外
        left < 0 && (left = 0)
        left > width && (left = width - odiv.offsetWidth)
        top < 0 && (top = 0)
        top > height && (top = height - odiv.offsetHeight)
        // 移动当前元素
        odiv.style.left = `${left}px`;
        odiv.style.top = `${top}px`;
      }
      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    }
  },
  created () {

  },
  beforeMount () {

  },
  mounted () {

  },
  watch: {},
}
</script>

<style lang='less' scoped>
.drag-content {
  position: relative;
  width: 500px;
  height: 500px;
  margin: auto;
  border: 1px dashed red;
}
.div-drag {
  position: absolute;
  width: 60px;
  height: 60px;
  background: red;
  cursor: move;
}
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值