drag.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. export default {
  2. bind(el, binding, vnode) {
  3. if (
  4. el.querySelector(".el-dialog__header") &&
  5. el.querySelector(".el-dialog")
  6. ) {
  7. const dialogHeaderEl = el.querySelector(".el-dialog__header");
  8. const dragDom = el.querySelector(".el-dialog");
  9. dialogHeaderEl.style.cssText += ";cursor:move;";
  10. dragDom.style.cssText += ";top:0;";
  11. const getStyle = (function () {
  12. if (window.document.currentStyle) {
  13. return (dom, attr) => dom.currentStyle[attr];
  14. } else {
  15. return (dom, attr) => getComputedStyle(dom, false)[attr];
  16. }
  17. })();
  18. dialogHeaderEl.onmousedown = (e) => {
  19. const disX = e.clientX - dialogHeaderEl.offsetLeft;
  20. const disY = e.clientY - dialogHeaderEl.offsetTop;
  21. const dragDomWidth = dragDom.offsetWidth;
  22. const dragDomHeight = dragDom.offsetHeight;
  23. const screenWidth = document.body.clientWidth;
  24. const screenHeight = document.body.clientHeight;
  25. const minDragDomLeft = dragDom.offsetLeft;
  26. const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth;
  27. const minDragDomTop = dragDom.offsetTop;
  28. const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomHeight;
  29. let styL = getStyle(dragDom, "left");
  30. let styT = getStyle(dragDom, "top");
  31. if (styL.includes("%")) {
  32. styL = +document.body.clientWidth * (+styL / 100);
  33. styT = +document.body.clientHeight * (+styT / 100);
  34. } else {
  35. styL = +styL.replace(/\px/g, "");
  36. styT = +styT.replace(/\px/g, "");
  37. }
  38. document.onmousemove = function (e) {
  39. let left = e.clientX - disX;
  40. let top = e.clientY - disY;
  41. if (-left > minDragDomLeft) {
  42. left = -minDragDomLeft;
  43. } else if (left > maxDragDomLeft) {
  44. left = maxDragDomLeft;
  45. }
  46. if (-top > minDragDomTop) {
  47. top = -minDragDomTop;
  48. } else if (top > maxDragDomTop) {
  49. top = maxDragDomTop;
  50. }
  51. dragDom.style.cssText += `;left:${left + styL}px;top:${
  52. top + styT
  53. }px;`;
  54. vnode.child.$emit("dragDialog");
  55. };
  56. document.onmouseup = function (e) {
  57. document.onmousemove = null;
  58. document.onmouseup = null;
  59. };
  60. };
  61. }
  62. },
  63. };