drag.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * v-dialogDrag 弹窗拖拽
  3. * Copyright (c) 2019 ruoyi
  4. */
  5. export default {
  6. bind(el, binding, vnode, oldVnode) {
  7. const value = binding.value
  8. if (value == false) return
  9. // 获取拖拽内容头部
  10. const dialogHeaderEl = el.querySelector('.el-dialog__header');
  11. const dragDom = el.querySelector('.el-dialog');
  12. dialogHeaderEl.style.cursor = 'move';
  13. // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
  14. const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);
  15. dragDom.style.position = 'absolute';
  16. dragDom.style.marginTop = 0;
  17. let width = dragDom.style.width;
  18. if (width.includes('%')) {
  19. width = +document.body.clientWidth * (+width.replace(/\%/g, '') / 100);
  20. } else {
  21. width = +width.replace(/\px/g, '');
  22. }
  23. dragDom.style.left = `${(document.body.clientWidth - width) / 2}px`;
  24. // 鼠标按下事件
  25. dialogHeaderEl.onmousedown = (e) => {
  26. // 鼠标按下,计算当前元素距离可视区的距离 (鼠标点击位置距离可视窗口的距离)
  27. const disX = e.clientX - dialogHeaderEl.offsetLeft;
  28. const disY = e.clientY - dialogHeaderEl.offsetTop;
  29. // 获取到的值带px 正则匹配替换
  30. let styL, styT;
  31. // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
  32. if (sty.left.includes('%')) {
  33. styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100);
  34. styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100);
  35. } else {
  36. styL = +sty.left.replace(/\px/g, '');
  37. styT = +sty.top.replace(/\px/g, '');
  38. };
  39. // 鼠标拖拽事件
  40. document.onmousemove = function (e) {
  41. // 通过事件委托,计算移动的距离 (开始拖拽至结束拖拽的距离)
  42. const l = e.clientX - disX;
  43. const t = e.clientY - disY;
  44. let finallyL = l + styL
  45. let finallyT = t + styT
  46. // 移动当前元素
  47. dragDom.style.left = `${finallyL}px`;
  48. dragDom.style.top = `${finallyT}px`;
  49. };
  50. document.onmouseup = function (e) {
  51. document.onmousemove = null;
  52. document.onmouseup = null;
  53. };
  54. }
  55. }
  56. };