Untitled
unknown
plain_text
2 years ago
1.4 kB
7
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.clientX - rect.left + window.scrollX,
y: e.clientY - rect.top + window.scrollY,
});
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.clientX - rect.left + window.scrollX,
y: e.clientY - rect.top + window.scrollY,
});
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...