纯js实现弹幕效果

以下代码是通过angular实现的,需要使用前自行修改成所使用的框架。

html部分

<div class="commentsContainer" id="commentContainer">
  <div *ngFor="let item of commentList">
    <div class="bullet" [ngStyle]="{top: item.height+'px'}">{{item.text}}</div>
  </div>
</div>

<div class="writeComment">
  <input class="commentInput" type="text" placeholder="请输入弹幕" [(ngModel)]="commentContent">
  <button (click)="postComment()">发送</button>
</div>

ts部分

commentList: Array<any> = []
commentContent: string = ""

//随机函数
getRandom(min: number, max: number): number {
 let num: number = Math.floor(Math.random() * (max - min))
  return num
}

postComment() {
  this.commentList.push({text:this.commentContent,height: this.getRandom(0,40)})

  setTimeout(() => {
    this.commentList.shift()
  }, 8000);

  this.commentContent = '' //clear content
}

css部分

/*从左往右的动画*/
@-webkit-keyframes moveto{
 0% {
    left: 0px;
  }

  100%{
    left: 100%;
  }
}

.bullet {
  font-size: 22px;
  position: absolute;
  -webkit-animation: moveto 15s ease-out;
}

版权声明:本文为Crayon111原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。