drag.js 2.2 KB

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