面试题答案
一键面试整体思路
- 使用React - spring库:它提供了简单且强大的方式来创建动画。通过监听鼠标事件(如
mousedown
、mousemove
、mouseup
),根据dragSpeed
和dragDirection
来计算元素的位置变化,并通过动画库将这些变化以平滑的动画呈现。 - CSS动画:同样监听鼠标事件,计算位置变化,然后通过CSS的
transition
属性来实现平滑过渡效果。这里以React - spring为例。
核心代码
import React, { useState } from 'react';
import { useSpring, animated } from'react-spring';
const DraggableElement = ({ dragSpeed, dragDirection }) => {
const [isDragging, setIsDragging] = useState(false);
const [startPosition, setStartPosition] = useState({ x: 0, y: 0 });
const [currentPosition, setCurrentPosition] = useState({ x: 0, y: 0 });
const handleMouseDown = (e) => {
setIsDragging(true);
setStartPosition({ x: e.pageX, y: e.pageY });
setCurrentPosition({ x: currentPosition.x, y: currentPosition.y });
};
const handleMouseMove = (e) => {
if (isDragging) {
const dx = e.pageX - startPosition.x;
const dy = e.pageY - startPosition.y;
if (dragDirection === 'horizontal') {
setCurrentPosition({ x: currentPosition.x + dx * dragSpeed, y: currentPosition.y });
} else {
setCurrentPosition({ x: currentPosition.x, y: currentPosition.y + dy * dragSpeed });
}
}
};
const handleMouseUp = () => {
setIsDragging(false);
};
const springProps = useSpring({
x: currentPosition.x,
y: currentPosition.y
});
return (
<animated.div
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
style={{
position: 'absolute',
left: springProps.x,
top: springProps.y,
backgroundColor: 'lightblue',
width: '50px',
height: '50px'
}}
/>
);
};
export default DraggableElement;
在上述代码中:
useState
用于管理拖动状态(isDragging
)、起始位置(startPosition
)和当前位置(currentPosition
)。handleMouseDown
事件记录起始位置并设置拖动状态为true
。handleMouseMove
事件根据dragDirection
和dragSpeed
更新当前位置。handleMouseUp
事件结束拖动状态。useSpring
用于创建平滑动画,将当前位置应用到元素的left
和top
属性上。