=== Three methods to focus on ===
- OnMouseDown press
- OnMouseMove drag
- OnMouseUp lift
Implementation steps
Set the window press lift event
useEffect(() => {
window.onmousedown = () => mouseDown()
window.onmouseup = e => mouseUp(e)
}, [])
Copy the code
Set the drag event for the div tag
<div id={styles.div_super_box}>
<div onClick={() => setIsSel(false)} style={{ width: 1280, height: 720, backgroundColor: 'yellow', overflow: 'hidden' }}>
<div id={isSel ? styles.div_box_click : styles.div_box} onClick={(e) => {
setIsSel(true);
e.stopPropagation();
}}
style={{ transform: `translateX(${translateX}px) translateY(${translateY}px)` }}
onMouseMove={e => onMove(e)} >
<img style={{ width: '100%', height: '100%' }} alt={''} src={max_bg_3}></img>
</div>
</div>
</div>
Copy the code
The complete code
import styles from './test.module.css' import React, { useEffect, useState } from 'react' import max_bg_3 from '.. /.. /assets/images/max_bg_3.png' const Test = () => {// Whether to move const [isMoving, setIsMoving] = useState(false) const [lastX, setLastX] = useState(0); const [lastY, setLastY] = useState(0); const [translateX, setTranslateX] = useState(0); const [translateY, setTranslateY] = useState(0); const [isSel, setIsSel] = useState(true) useEffect(() => { window.onmousedown = () => mouseDown() window.onmouseup = e => mouseUp(e) }, []) // mouseDown const mouseDown = () => {setIsMoving(true)} // mouse move const onMove = (e) => isSel && move(e) const move = (e) => { e.stopPropagation(); e.preventDefault(); if (lastX && lastY) { let dx = e.clientX - lastX let dy = e.clientY - lastY setTranslateX(translateX + dx); setTranslateY(translateY + dy); } setLastX(e.clientX) setLastY(e.clientY) } const mouseUp = (e) => { if (e ! = null) { } setIsMoving(false) } return (<div id={styles.div_super_box}> <div onClick={() => setIsSel(false)} style={{ width: 1280, height: 720, backgroundColor: 'yellow', overflow: 'hidden' }}> <div id={isSel ? styles.div_box_click : styles.div_box} onClick={(e) => { setIsSel(true); e.stopPropagation(); }} style={{ transform: `translateX(${translateX}px) translateY(${translateY}px)` }} onMouseMove={e => onMove(e)} > <img style={{ width: '100%', height: '100%' }} alt={''} src={max_bg_3}></img> </div> </div> </div>) } export default TestCopy the code