24ea08aec831a3b018d6f6757a3b009bc724d34a.svn-base 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. export default {
  2. bind(el, binding, vnode) {
  3. const dialogHeaderEl = el.querySelector('.el-dialog__header')
  4. const dragDom = el.querySelector('.el-dialog')
  5. dialogHeaderEl.style.cssText += ';cursor:move;'
  6. dragDom.style.cssText += ';top:0px;'
  7. // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
  8. const getStyle = (function() {
  9. if (window.document.currentStyle) {
  10. return (dom, attr) => dom.currentStyle[attr]
  11. } else {
  12. return (dom, attr) => getComputedStyle(dom, false)[attr]
  13. }
  14. })()
  15. dialogHeaderEl.onmousedown = (e) => {
  16. // 鼠标按下,计算当前元素距离可视区的距离
  17. const disX = e.clientX - dialogHeaderEl.offsetLeft
  18. const disY = e.clientY - dialogHeaderEl.offsetTop
  19. const dragDomWidth = dragDom.offsetWidth
  20. const dragDomHeight = dragDom.offsetHeight
  21. const screenWidth = document.body.clientWidth
  22. const screenHeight = document.body.clientHeight
  23. const minDragDomLeft = dragDom.offsetLeft
  24. const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth
  25. const minDragDomTop = dragDom.offsetTop
  26. const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomHeight
  27. // 获取到的值带px 正则匹配替换
  28. let styL = getStyle(dragDom, 'left')
  29. let styT = getStyle(dragDom, 'top')
  30. if (styL.includes('%')) {
  31. styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100)
  32. styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100)
  33. } else {
  34. styL = +styL.replace(/\px/g, '')
  35. styT = +styT.replace(/\px/g, '')
  36. }
  37. document.onmousemove = function(e) {
  38. // 通过事件委托,计算移动的距离
  39. let left = e.clientX - disX
  40. let top = e.clientY - disY
  41. // 边界处理
  42. if (-(left) > minDragDomLeft) {
  43. left = -minDragDomLeft
  44. } else if (left > maxDragDomLeft) {
  45. left = maxDragDomLeft
  46. }
  47. if (-(top) > minDragDomTop) {
  48. top = -minDragDomTop
  49. } else if (top > maxDragDomTop) {
  50. top = maxDragDomTop
  51. }
  52. // 移动当前元素
  53. dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`
  54. // emit onDrag event
  55. vnode.child.$emit('dragDialog')
  56. }
  57. document.onmouseup = function(e) {
  58. document.onmousemove = null
  59. document.onmouseup = null
  60. }
  61. }
  62. }
  63. }