vue实现组件拖拽功能

11 篇文章 0 订阅
/*
组件拖拽插件 by lwj
使用方法:导入此插件,使用mixins混入对象
在需要拖拽的元素添加如下方法即可:
<div οndragstart="return false;" οndrοp="return false;" draggable="false" 
@mousedown="onMousedown($event, 'lvs-broadcast__m-header')">
*/
export const dragPlugin = {
  data() {
    return {
      isDown: false, //鼠标是否按下
      moveX: 0,
      moveY: 0, //实时监听鼠标位置
      click_x: 0,
      click_y: 0, //鼠标按下瞬间的位置
      div_x: 0,
      div_y: 0, //元素的位置,
      elementObj: null,
      clickCicleTime: '' //根据mousedown和up的时间差判断是否是点击事件
    }
  },

  methods: {
    onMousedown(e, className) {
      if (!e || !className) {
        return;
      }
      this.clickCicleTime = + new Date()
      this.click_x = e.clientX
      this.click_y = e.clientY
      this.isDown = true
      //获取DIV的位置
      this.elementObj = document.getElementsByClassName(className)[0];
      this.div_x = this.elementObj.offsetLeft
      this.div_y = this.elementObj.offsetTop

      let self = this;
      document.addEventListener('mousemove', function (e) {
        self.dragMouseMove(e);
      })
      this.elementObj.addEventListener('mouseup', function (e) {
        e.stopPropagation();
        e.preventDefault();
        self.onMouseup(e);
      })
    },
    onMouseup(e) {
      var event = (e) ? e : window.event;
      event.stopPropagation();// 其它浏览器下阻止冒泡
      event.preventDefault();

      let _clickCicleTime = + new Date()
      let differTime = _clickCicleTime - this.clickCicleTime
      if (differTime < 200 && this.isDown) {
        if (this.elementObj && this.elementObj.className == 'lvs-broadcast__zoom-out') {
          this.showPanel = !this.showPanel;
        }
      }
      this.isDown = false
      this.mouseMoveX = 0
      this.mouseMoveY = 0
      document.removeEventListener('mousemove', this.dragMouseMove)
      this.elementObj.removeEventListener('mouseup', this.onMouseup)
    },
    dragMouseMove(e) {
      this.moveX = e.clientX
      this.moveY = e.clientY
      //计算鼠标移动偏移量
      this.mouseMoveX = this.moveX - this.click_x
      this.mouseMoveY = this.moveY - this.click_y
      //当鼠标按下时才执行
      if (this.isDown) {
        var new_div_x = this.div_x + this.mouseMoveX
        var new_div_y = this.div_y + this.mouseMoveY
        this.elementObj.style.left = new_div_x + 'px'
        this.elementObj.style.top = new_div_y + 'px'
      }
    }
  }
}


调用:
import { dragPlugin } from 'xxx'
  mixins: [dragPlugin],

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值