drag2.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export default {
  2. bind(el, binding,vNode,vNode1) {
  3. el.style.cursor = 'move'
  4. el.onmousedown = function(e) {
  5. //鼠标按下,计算当前元素距离可视区的距离
  6. let disx = e.pageX - el.offsetLeft
  7. let disy = e.pageY - el.offsetTop
  8. document.onselectstart = function(e) {
  9. return false;
  10. };//解决拖动会选中文字的问题
  11. document.onmousemove = function(e) {
  12. let x = e.pageX - disx
  13. let y = e.pageY - disy
  14. let maxX = document.getElementById("box").clientWidth - parseInt(window.getComputedStyle(el).width)
  15. let maxY = document.getElementById("box").clientHeight - parseInt(window.getComputedStyle(el).height)
  16. // console.log('maxX==>',maxX)
  17. // console.log('maxY==>',maxY)
  18. if (x < 0) {
  19. x = 0
  20. } else if (x > maxX) {
  21. x = maxX
  22. }
  23. if (y < 0) {
  24. y = 0
  25. } else if (y > maxY) {
  26. y = maxY
  27. }
  28. el.style.left = x + 'px'
  29. el.style.top = y + 'px'
  30. //将此时的位置传出去
  31. // binding.value({
  32. // x: x + 'px',
  33. // y: y + 'px'
  34. // })
  35. };
  36. document.onmouseup = function(e) {
  37. // console.log(e.target.innerHTML,'innerHTML===')
  38. let str = e.target.innerHTML;
  39. let result = el.getElementsByClassName('myspan')[0].innerText;
  40. let x = e.pageX - disx
  41. let y = e.pageY - disy
  42. let maxX = document.getElementById("box").clientWidth - parseInt(window.getComputedStyle(el).width)
  43. let maxY = document.getElementById("box").clientHeight - parseInt(window.getComputedStyle(el).height)
  44. // console.log('maxX==>',maxX)
  45. // console.log('maxY==>',maxY)
  46. if (x < 0) {
  47. x = 0
  48. } else if (x > maxX) {
  49. x = maxX
  50. }
  51. if (y < 0) {
  52. y = 0
  53. } else if (y > maxY) {
  54. y = maxY
  55. }
  56. el.style.left = x + 'px'
  57. el.style.top = y + 'px'
  58. //将此时的位置传出去
  59. binding.value({
  60. x: x + 'px',
  61. y: y + 'px',
  62. myId:result
  63. })
  64. document.onmousemove = null;
  65. document.onmouseup = null;
  66. };
  67. };
  68. }
  69. }