MoveService.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. export default class MoveService {
  2. constructor(DOM) {
  3. if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
  4. this.DviceType = true
  5. } else {
  6. this.DviceType = false
  7. }
  8. this.movedom = null
  9. this.w = document.body.clientWidth
  10. this.h = document.body.clientHeight
  11. this.PX = 0
  12. this.PY = 0
  13. this.domw = 0
  14. this.domh = 0
  15. this.on(DOM)
  16. }
  17. /**
  18. * 移动
  19. */
  20. mousemove(event) {
  21. const e = event || window.event
  22. const x = this.DviceType ? e.touches[0].clientX : e.clientX
  23. const y = this.DviceType ? e.touches[0].clientY : e.clientY
  24. const mx = x - this.PX
  25. const my = y - this.PY
  26. const outx = this.w - this.domw
  27. const outy = this.h - this.domh
  28. this.movedom.style.left = `${mx}px`
  29. this.movedom.style.top = `${my}px`
  30. if (mx >= outx) {
  31. this.movedom.style.left = `${outx}px`
  32. }
  33. if (my >= outy) {
  34. this.movedom.style.top = `${outy}px`
  35. }
  36. if (mx <= 0) {
  37. this.movedom.style.left = '0px'
  38. }
  39. if (my <= 0) {
  40. this.movedom.style.top = '0px'
  41. }
  42. }
  43. /**
  44. * 鼠标按下
  45. */
  46. mousedown(event) {
  47. // 获取点击DOM
  48. const e = event || window.event
  49. if (this.DviceType) {
  50. this.PX = e.touches[0].clientX - this.movedom.offsetLeft
  51. this.PY = e.touches[0].clientY - this.movedom.offsetTop
  52. this.movedom.ontouchmove = this.mousemove.bind(this)
  53. this.movedom.ontouchend = this.mouseup.bind(this)
  54. } else {
  55. this.PX = e.clientX - this.movedom.offsetLeft
  56. this.PY = e.clientY - this.movedom.offsetTop
  57. this.movedom.onmousemove = this.mousemove.bind(this)
  58. this.movedom.onmouseup = this.mouseup.bind(this)
  59. }
  60. }
  61. /**
  62. * 鼠标松开
  63. */
  64. mouseup() {
  65. this.off()
  66. }
  67. /**
  68. * 监听鼠标
  69. * @param dom dom元素
  70. */
  71. on(dom) {
  72. this.movedom = dom
  73. try {
  74. if (this.DviceType) {
  75. this.movedom.ontouchstart = this.mousedown.bind(this)
  76. } else {
  77. this.movedom.onmousedown = this.mousedown.bind(this)
  78. }
  79. this.domw = parseInt(window.getComputedStyle(this.movedom).width)
  80. this.domh = parseInt(window.getComputedStyle(this.movedom).height)
  81. } catch (error) {
  82. console.warn('dom 获取失败')
  83. }
  84. }
  85. /**
  86. * 移除监听
  87. */
  88. off() {
  89. this.movedom.onmousemove = null
  90. this.movedom.onmouseup = null
  91. this.movedom.ontouchmove = null
  92. this.movedom.ontouchend = null
  93. }
  94. }