zoukankan      html  css  js  c++  java
  • 手写react弹幕效果

    思路:

      改变元素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;
    }
  • 相关阅读:
    数学
    ACM之路
    归并排序(分治法,nlogn,较为稳定)
    字典树基础模板
    c语言对象(函数,类,变量)的声明与定义
    typedef的高级用法---------理解函数声明
    4503: 两个串
    HDU 5972 Regular Number
    HDU 5215 Cycle
    Hihocoder #1513 : 小Hi的烦恼
  • 原文地址:https://www.cnblogs.com/zpfqi/p/13397882.html
Copyright © 2011-2022 走看看