DOM
拖拽线设置为局对定位,容器为相对定位
<divstyle={{width: '100%',height: '100%',position: 'relative',}}><divid="guideX"className={`guideX ${isDraggingX ? 'dragging' : ''}`}style={styleX}// @ts-ignoreonMouseDown={handleMouseDownX}/>
</div>
.guideX {background-color: #aaa;height: 1px;position: absolute;z-index: 1001;
}.guideX:hover {cursor: move;
}
拖拽事件
1.记录当前是否被拖拽
const [isDraggingX, setIsDraggingX] = useState(false);
2.鼠标按下时状态标记为正在拖拽
const handleMouseDownX = (event: MouseEvent) => {event.preventDefault();setIsDraggingX(true);
};
3.拖拽时改变辅助线的位置
const handleMouseMove = (event: MouseEvent) => {event.preventDefault();if (isDraggingX) {setStyleX({...styleX,top: event.clientY,});}
};
4.结束拖拽时状态标记为非拖拽
const handleMouseDownX = (event: MouseEvent) => {event.preventDefault();setIsDraggingX(true);
};
完整代码
import { useEffect, useState } from 'react';
import './index.less';const Image = () => {const [styleX, setStyleX] = useState({width: '100%',left: 0,top: 0,});const [isDraggingX, setIsDraggingX] = useState(false);useEffect(() => {const handleMouseMove = (event: MouseEvent) => {event.preventDefault();if (isDraggingX) {setStyleX({...styleX,top: event.clientY,});}};const handleMouseUp = (event: MouseEvent) => {event.preventDefault();setIsDraggingX(false);};document.addEventListener('mousemove', handleMouseMove);document.addEventListener('mouseup', handleMouseUp);return () => {document.removeEventListener('mousemove', handleMouseMove);document.removeEventListener('mouseup', handleMouseUp);};}, [isDraggingX, styleX]);const handleMouseDownX = (event: MouseEvent) => {event.preventDefault();setIsDraggingX(true);};return (<divstyle={{width: '100%',height: '100%',position: 'relative',}}><divid="guideX"className={`guideX ${isDraggingX ? 'dragging' : ''}`}style={styleX}// @ts-ignoreonMouseDown={handleMouseDownX}/></div>);
};export default Image;