在这里,在水平滚动div的代码中,div是滚动消失的。尝试弄清楚如何使其仅在容器的宽度内可滚动
https://codesandbox.io/s/fast-morning-qe9s9?file=/src/App.js:0-1188
const quickAndDirtyStyle = {
width: "200px",
height: "200px",
background: "#FF9900",
color: "#FFFFFF",
display: "flex",
justifyContent: "center",
alignItems: "center"
};
const DraggableComponent = () => {
const [pressed, setPressed] = useState(false);
const [position, setPosition] = useState({ x: 0 });
const ref = useRef();
// Monitor changes to position state and update DOM
useEffect(() => {
if (ref.current) {
ref.current.style.transform = `translate(${position.x}px)`;
}
}, [position]);
// Update the current position if mouse is down
const onMouseMove = (event) => {
if (pressed) {
setPosition({
x: position.x + event.movementX //needed help here-trying to fix the scroll inside container
});
}
event.stopPropagation();
event.preventDefault();
};
return (
<div
ref={ref}
style={quickAndDirtyStyle}
onMouseMove={onMouseMove}
onMouseDown={() => setPressed(true)}
onMouseUp={() => setPressed(false)}
onMouseLeave={() => setPressed(false)}
>
<p>{pressed ? "Dragging..." : "Press to drag"}</p>
</div>
);
};
export default DraggableComponent; ```发布于 2020-12-14 19:19:25
您可以在可拖动的元素周围添加一个额外的包装器,计算该元素的宽度,并使用它与该元素的下一个位置进行比较。
起始X位置从可拖动元素的左上角开始,因此最后一个可能的X位置应填充条件nextXPosition + elementWidth <= containerWidth nextXPosition <= 0. nextXPosition + elementWidth <= containerWidth
下面是可用的codesandbox示例。https://codesandbox.io/s/funny-margulis-782xn?file=/src/App.js
https://stackoverflow.com/questions/65287568
复制相似问题