Train of thought to sort out

To do this, as the name implies, the DOM moves when the mouse moves;

Take the mousedown and mouseup actions and add some logic to those three actions.

Click (mousedown) : get the current position of the mouse and the position of the target DOM, get the initial movement value of these two;

Mousemove: When the mouse moves, obtain the current position to obtain the difference of the mouse movement, which is also the movement distance of the target DOM. That is:

Mouse position after mouse movement – mouse starting position = target DOM position after mouse movement – target DOM starting position

So calculate the difference value after mouse movement, subtract the target DOM value is equal to the target DOM position after movement;

Code implementation

To move, we have to translate. To use this property, we need to verify which transform the browser supports.

Const getTransform = () => {let transform = "; const divStyle = document.createElement('div').style, _transforms = ['transform', 'webkitTransform', 'MozTransform', 'msTansform', 'OTransform'], len = _transforms.length; for(let i = 0; i < len; i++) { if(_transforms[i] in divStyle) { return transform = _transforms[i] } } return transform }Copy the code

If the browser doesn’t support it, use the left/top location to move it around.

Consider some partners are still using IE, although immediately delisted (chuckles), but still do compatibility;

Const getStyle = (elem, property) => {return window.getcomputedStyle? window.getComputedStyle(elem, false)[property] : elem.currentStyle[property] }Copy the code

With these two methods in place, you’re ready to start the formal code

Start by setting the default element values

Let startX = 0 target startX position let startY = 0 target startY position let isDrop = false get whether to start moving let sourceX = 0 target end X position let sourceY = 0 Const getTargetPos = elem => {let pos = {x: 10, Y: 0 } const transform = getTransform() if(transform) { const transformValue = getStyle(elem, transform) if(transformValue === 'none') { elem.style[transform] = 'translate(0, 0)' return pos } else { const temp = transformValue.match(/-? \d+/g) return pos = { x: parseInt(temp[4].trim()), y: parseInt(temp[5].trim()), } } } else { if(getStyle(elem, 'position') == 'static') { elem.style.position = 'relative' return pos } else { const x = parseInt(getStyle(elem, 'left') ? getStyle(elem, 'left') : 0) const y = parseInt(getStyle(elem, 'top') ? getStyle(elem, 'top') : 0) return pos = { x: x, y: y } } } }Copy the code

Sets the position of the element

  const setTargetPos = (elem, pos) => {
    const transform = getTransform()
    if(transform) {
      elem.style[transform] = 'translate('+pos.x + 'px, '+ pos.y +'px)'
    } else {
      elem.style.left = pos.x + 'px'
      elem.style.top = pos.y + 'px'
    }
    return elem
 }
Copy the code

Mouse click

  const start = event => {
    console.log('start')
  const autumn = document.querySelector('.autumn')
    startX = event.pageX
    startY = event.pageY
    const pos = getTargetPos(autumn)
    sourceX = pos.x
    sourceY = pos.y
    isDrop = true
  }
Copy the code

When the mouse moves

  const move = event => {
    console.log('move')
    if (isDrop) {
      const autumn = document.querySelector('.autumn')
      const currentX = event.pageX 
     const currentY = event.pageY 
       const distanceX = currentX - startX
      const distanceY = currentY - startY 
     setTargetPos(autumn, {
        x: (sourceX + distanceX).toFixed(),
        y: (sourceY + distanceY).toFixed(),
        })
    } else {
      return
    }
  }
Copy the code

Mouse lift end

const end = () => { document.removeEventListener('mousemove', move) document.removeEventListener('mouseup', End) isDrop = falseCopy the code

Use hooks this time

  useEffect(() => {
  const autumn = document.querySelector('.autumn')
    autumn.addEventListener('mousedown', start, false)
    document.onmousemove = move
    autumn.addEventListener('mouseup', end, false)
  }, [])  
Copy the code

The page elements

  return (
    <div className="autumn"
         style={{ width: '30px', height: '20px', backgroundColor: 'pink' }}
    >
        {props.button()}
    </div>
  )
Copy the code

In order not to write style files, this time write line, do not spray oh

Article borrowed from: development and decryption of JavaScript core Technology