随着div位置的变化平滑地给div设置动画 [英] Smoothly animate a div as its position changes
问题描述
我有一个绝对定位的div:
I have an absolutely positioned div:
class MyDiv extends React.Component {
state = {
stepCount: 0
};
componentDidMount(){
setInterval(() => {
this.setState({ stepCount: this.state.stepCount + 1 })
}, 1000);
}
render(){
return (<div style={{ left: this.state.stepCount * 10 + "%" }} />);
}
}
CSS
div { transition: 1s linear; }
每秒钟,我将div左移10%。
我希望过渡看起来平滑,但会有一点停顿。
Every second, I translate the div left by 10%. I want the transitions to look smooth, but there is a slight stutter.
示例:
https:/ /codepen.io/anon/pen/QoNGbQ
推荐答案
您最好使用CSS转换或模块,例如react-spring,但如果它们都不适合您,则您需要 requestAnimationFrame
。
You're probably best off using CSS transforms or a module such as react-spring, but if neither of them suit you then you want requestAnimationFrame
.
(CSS转换会使文字模糊 CSS过渡效果会使图像模糊/在Chrome中将图片移动1像素?,并且一次性使用,可能不希望外部模块捆绑加载)
(CSS Transforms can make text blurry CSS transition effect makes image blurry / moves image 1px, in Chrome? and for a one-off you might not want the bundle load of an external module)
https://codesandbox.io/s/pj9m554nkj
const animate = ({ timing, draw, duration }) => {
let start = performance.now();
const animateLoop = time => {
const durationFraction = Math.min(
1,
Math.max(0, (time - start) / duration)
);
const progress = timing(durationFraction);
draw(progress);
if (durationFraction < 1) {
requestAnimationFrame(animateLoop);
}
};
requestAnimationFrame(animateLoop);
};
const MovingDiv = ({ move, duration }) => {
const [pos, setPos] = useState(0);
useEffect(() => {
animate({
timing: fraction => move * fraction,
draw: progress => setPos(progress),
duration
});
}, []);
return <div className="MovingDiv" style={{ left: pos }} />;
};
然后您还可以在计时功能中使用easyIn / easeOut开始演奏,以增加弹力。 。 https://codesandbox.io/s/2w6ww8oymp
You can also then start playing with easeIn/easeOut in the timing function to add a bit of spring.. https://codesandbox.io/s/2w6ww8oymp
这篇关于随着div位置的变化平滑地给div设置动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!