Untitled
unknown
plain_text
2 years ago
1.3 kB
5
Indexable
import React, { useState, useRef } from 'react'; import { Box } from '@mui/material'; const DraggableText = () => { const [position, setPosition] = useState({ x: 0, y: 0 }); const [dragging, setDragging] = useState(false); const boxRef = useRef(); const onMouseDown = (e) => { setDragging(true); const rect = boxRef.current.getBoundingClientRect(); setPosition({ x: e.pageX - rect.left, y: e.pageY - rect.top, }); e.stopPropagation(); e.preventDefault(); }; const onMouseUp = (e) => { setDragging(false); e.stopPropagation(); e.preventDefault(); }; const onMouseMove = (e) => { if (!dragging) return; const rect = boxRef.current.getBoundingClientRect(); setPosition({ x: e.pageX - rect.left, y: e.pageY - rect.top, }); e.stopPropagation(); e.preventDefault(); }; return ( <Box ref={boxRef} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onMouseMove={onMouseMove} sx={{ position: 'relative', width: '100px', height: '100px', backgroundColor: 'lightgrey', '&::after': { content: '"abc"', position: 'absolute', top: `${position.y}px`, left: `${position.x}px`, } }} /> ); }; export default DraggableText;
Editor is loading...