弹窗拖拽指令

弹窗拖拽指令封装

import Vue from 'vue';
//使用Vue.directive()定义一个全局指令
//1.参数一:指令的名称,定义时指令前面不需要写v-
//2.参数二:是一个对象,该对象中有相关的操作函数
//3.在调用的时候必须写v-
const drag = Vue.directive('drag', {
  //1.指令绑定到元素上回立刻执行bind函数,只执行一次
  //2.每个函数中第一个参数永远是el,表示绑定指令的元素,el参数是原生js对象
  //3.通过el.focus()是无法获取焦点的,因为只有插入DOM后才生效
  bind: function (el) {},
  //inserted表示一个元素,插入到DOM中会执行inserted函数,只触发一次
  inserted: function (el) {
  //判断两种类型(弹窗具有头部,类包含Title;以及第二种不包含头部)
      if (el.firstChild.className.indexOf("Title") != -1) {
      const W = el.offsetWidth
      const H = el.offsetHeight
      const screenWidth = document.body.clientWidth;
      const screenHeight = document.documentElement.clientHeight;
      el.firstChild.onmousedown = function (e) {
          var disx = e.pageX - el.offsetLeft;
          var disy = e.pageY - el.offsetTop;
        document.onmousemove = function (e) {
            // el.style.cursor = 'move';
          const left = e.pageX - disx;
          const top = e.pageY - disy;

    //以下是进行弹窗拖拽边界处理(仅使用与我自己当前的项目,借用需修改)
          if (left <= 0) {
            el.style.left = 0 + 'px'
          } else if (left >= screenWidth - W) {
            el.style.left = screenWidth - W + 'px'
          } else {
            el.style.left = left + 'px'
          }
          if (top <= 0) {
            el.style.top = 0 + 'px'
          } else if (top >= screenHeight - H) {
            if (screenHeight < H) {
              el.style.top = 100 + 'px'
            } else {
              el.style.top = screenHeight - H + 'px'
            }
          } else {
            el.style.top = top + 'px'
          }
          // console.log(el.style.left, el.style.top);
        }
        document.onmouseup = function () {
          // el.style.cursor = 'default';
          document.onmousemove = document.onmouseup = null;
        }
      }
    } else {
      el.onmousedown = function (e) {
        var disx = e.pageX - el.offsetLeft;
        var disy = e.pageY - el.offsetTop;
        // console.log(e.pageX,el.offsetLeft);
        document.onmousemove = function (e) {
            // el.style.cursor = 'move';
            el.style.left = e.pageX - disx + 'px';
            el.style.top = e.pageY - disy + 'px';
            // console.log(el.style.left,el.style.top);
        }
        document.onmouseup = function () {
          // el.style.cursor = 'default';
          document.onmousemove = document.onmouseup = null;
        }
      }
    }
  },
  //当VNode更新的时候会执行updated,可以触发多次
  updated: function (el) {}
});
export default drag;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值