思路:
改變元素left,使用使其從右到左移動,transition來控制移動速度,使用transition-delay控制彈幕出現的順序
this.state = { //存放彈幕 bulletChatList:[{text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}, {text:'HAHAHAH'}], }, //存放新發的彈幕 sendBulletChatList:[] } componentDidMount() { document.title = "react彈幕" setTimeout(() => { let data = this.state.bulletChatList for(let i = 0;i < data.length; i++){ let num = Math.floor(Math.random() * 10) //每隔3s出現一條彈幕 data[i].transitionDelay = 3 * i + 's' data[i].left = '-200' //彈幕的高度隨機 data[i].top = num * 50 } this.setState({bulletChatList: data}) },100) } //發送彈幕 returnWord(){ let arr = this.state.sendBulletChatList let num = Math.floor(Math.random() * 10) let data = { text:'老鐵666', transitionDelay: '0s', top: num * 50, left: '110vw', } arr.push(data) this.setState({sendBulletChatList: arr}) setTimeout(() => { let info = this.state.sendBulletChatList info[ info.length - 1 ].left = '-200' this.setState({sendBulletChatList: info}) },30) } //渲染彈幕 render() { return ( <div className='bullet-chat'> { this.state.bulletChatList.map((item, index) => { return( <div className='' style={{top:`${item.top}rem`,left:`${item.left}px`,'transition-delay':`${item.transitionDelay}`}}> {item.text} </div> ) })} { this.state.sendBulletChatList.map((item, index) => { return( <div className='' style={{top:`${item.top}rem`,left:`${item.left}px`,'transition-delay':`${item.transitionDelay}`}}> {item.text} </div> ) })} </div> )}
css: .bullet-chat{ heigth:100vh; position: relative } .bullet-chat div{ position: absolute; transition: left linear 8s; }