[英]Dynamicaly animate elements css
所以,我正在编写一个横向旋转(从右到左)的轮盘赌,我想知道是否有任何方法可以动态使用@keyframes,所以我可以使用 translateX() 和根据轮盘结果的值(The轮盘赌在背景图像中)。 例如:轮盘结果为 5。客户端从服务器接收结果,轮盘转换 X 像素停止在相应的数字。
这是轮盘赌代码:
import React, { useState, useEffect } from "react";
import { socket } from "../../App.js";
import "./roulette.css";
export default class Roulette extends React.Component {
constructor(props) {
super(props);
this.socket = socket;
this.roulette = React.createRef();
this.state = {
result: null,
};
}
componentDidMount() {
this.setState({
backgroundPositionX: (this.roulette.current.offsetWidth - 78) / 2
});
this.socket.on("roulette.roll", position => {
//TODO: Retrieve from the server how much pixels should be translated
});
}
render() {
return (
<div className="main-r flex items-center justify-center">
<div ref={this.roulette} className="roulette relative">
<div
style={{backgroundPosition: this.state.backgroundPositionX + "px" + "0"}
className="roulette-bg h-full w-full" //The roulette background image, that is suposed to translate when the result is give is in this div
></div>
<div className="roulette-marker absolute"></div>
</div>
</div>
);
}
}
您可以在componentDidMount()
中设置它,如下所示:
export default class Roulette extends React.Component {
constructor(props) {
super(props);
this.socket = socket;
this.roulette = React.createRef();
this.state = {
result: null,
backgroundPositionX: null
};
}
componentDidMount() {
this.setState({
backgroundPositionX: (this.roulette.current.offsetWidth - 78) / 2
});
this.socket.on("roulette.roll", position => {
this.setState({
backgroundPositionX: position
});
//TODO: Retrieve from the server how much pixels should be translated
});
}
render() {
return (
<div className="main-r flex items-center justify-center">
<div ref={this.roulette} className="roulette relative">
<div
style={{backgroundPosition: this.state.backgroundPositionX + "px"}
className="roulette-bg h-full w-full" //The roulette background image, that is suposed to translate when the result is give is in this div
></div>
<div className="roulette-marker absolute"></div>
</div>
</div>
);
}
}
或者您可以使用 js 使用ElementCSSInlineStyle
功能设置页面上元素的样式。 在这里讨论。
我相信你会在你的componentDidMount()
中加入这样的东西(使用@yuri-gor 提到的翻译):
const bgElement = window.document.querySelector('.roulette-bg');
bgElement.style.transform = 'translateX(42px)';
如果我正确地满足了您的要求-您需要 CSS过渡,而不是关键帧。
transition: transform 5s;
element.style.transform = 'translateX(42px)';
请注意,最好通过更改变换来制作动画 - 它会渲染得更平滑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.