这段代码会在页面上创建一个全屏的弹幕容器,然后定义了一个弹幕类和一个弹幕管理类。弹幕类用于创建单个弹幕,弹幕管理类用于管理多个弹幕的滚动。在页面加载完成后,我们可以通过调用弹幕管理器的addDanmu方法来添加弹幕,然后调用start方法开始弹幕滚动。弹幕滚动的实现是通过定时器不断更新每个弹幕的位置,并判断弹幕是否超出屏幕,如果超出则从弹幕容器中移除。
HTML:
<div id="danmu"></div>
CSS:
#danmu {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
JS:
// 定义弹幕类
class Danmu {
  constructor(text, color) {
    this.text = text;
    this.color = color;
    this.speed = Math.random() * 5 + 5; // 随机速度
    this.x = window.innerWidth; // 初始位置在屏幕右侧
    this.y = Math.random() * window.innerHeight; // 随机高度
    this.element = document.createElement('div');
    this.element.style.position = 'absolute';
    this.element.style.whiteSpace = 'nowrap';
    this.element.style.color = this.color;
    this.element.innerText = this.text;
    document.getElementById('danmu').appendChild(this.element);
  }
  // 更新弹幕位置
  update() {
    this.x -= this.speed;
    this.element.style.transform = `translate(${this.x}px, ${this.y}px)`;
  }
  // 判断弹幕是否超出屏幕
  isOutOfScreen() {
    return this.x + this.element.clientWidth < 0;
  }
}
// 定义弹幕管理类
class DanmuManager {
  constructor() {
    this.danmus = [];
    this.timer = null;
  }
  // 添加弹幕
  addDanmu(text, color) {
    const danmu = new Danmu(text, color);
    this.danmus.push(danmu);
  }
  // 开始弹幕滚动
  start() {
    this.timer = setInterval(() => {
      for (let i = 0; i < this.danmus.length; i++) {
        const danmu = this.danmus[i];
        danmu.update();
        if (danmu.isOutOfScreen()) {
          danmu.element.remove();
          this.danmus.splice(i, 1);
          i--;
        }
      }
    }, 16);
  }
  // 停止弹幕滚动
  stop() {
    clearInterval(this.timer);
    this.timer = null;
  }
}
// 创建弹幕管理器
const danmuManager = new DanmuManager();
// 添加弹幕
danmuManager.addDanmu('购买成功!', 'red');
danmuManager.addDanmu('感谢您的支持!', 'green');
danmuManager.addDanmu('再来一单吧!', 'blue');
// 开始弹幕滚动
danmuManager.start();
以上就是模板兔向大家提供的一个简单的购买订单弹幕功能。


0 个评论