Vue 指令 拖动元素


export default {
  data() {
    return {
      windowWidth:0,
      windowHeight:0
    };
  },
  directives: {
    drag (el,binding,vnode) {
      let oDiv = el,firstTime = '',lastTime = '';
      let _this = vnode.context;
      document.onselectstart = function () {
        // return false
      }
      oDiv.onmousedown = function (e) {
        document.getElementById('dragbtn').setAttribute('data-draggable',false);
        firstTime = new Date().getTime();
        let disX = e.clientX - oDiv.offsetLeft
        let disY = e.clientY - oDiv.offsetTop
        document.onmousemove = function (e) {
          let l = e.clientX - disX
          let t = e.clientY - disY
          if(l < 0){
            l = 0;
          }else if(l > _this.windowWidth - 56){
            l = _this.windowWidth - 56;
          }
          if(t < 0){
            t = 0;
          }else if(t > _this.windowHeight - 56){
            t = _this.windowHeight - 56;
          }
          oDiv.style.left = l + 'px'
          oDiv.style.top = t + 'px'
        }
        document.onmouseup = function (e) {
          document.onmousemove = null
          document.onmouseup = null
          lastTime = new Date().getTime();
          if( (lastTime - firstTime) < 200){
            document.getElementById('dragbtn').setAttribute('data-draggable',true);
          }
        }
        return false
      }
    }
  },
  mounted(){
      this.windowWidth = document.body.clientWidth;
      this.windowHeight = document.documentElement.clientHeight;
      window.onresize = () => {
        return (() => {
          this.windowWidth = document.body.clientWidth;
          this.windowHeight = document.documentElement.clientHeight;
          document.getElementById('dragbtn').style.left = this.windowWidth-56 +'px';
          document.getElementById('dragbtn').style.top = this.windowHeight-56 +'px';
        })();
      };
  },
  methods: {
    mousedowm (e) { 
      this.mouseDownX = e.pageX
      this.mouseDownY = e.pageY
      this.flag = true
    },
    mousemove (e) {
      if (this.flag) {
        console.log('e :', e)
      }
    },
  }
}

拖拽元素,并且设定边界。

html:

<div class="tips" @click="gotoSugges" title="建议反馈" v-drag data-draggable="false" id="dragbtn"></div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值