关于javascript:基于ES6利用观察者模式完成视频弹幕功能

8次阅读

共计 1134 个字符,预计需要花费 3 分钟才能阅读完成。

bullet.js 文件如下

import TimeManager from "./TimeManager.js";

export default class Bullet{
    rect;
    x;
    speed=2;
    width;
    col;
    constructor(txt){this.elem=this.createElem(txt);
    }
    createElem(txt){if(this.elem) return this.elem;
        var div = document.createElement("div");
        this.randomColor();
        Object.assign(div.style,{
            whiteSpace: "nowrap",
            position:"absolute",
            fontSize:"20px",
            color:this.col
        })
        div.textContent=txt
        return div;
    }
    randomColor() {
        this.col = "#";
        for (var i = 0; i < 6; i++) {this.col += Math.floor(Math.random() * 16).toString(16);
        }
    }
    appendTo(parent){if(typeof parent==="string") parent=document.querySelector(parent);
        parent.appendChild(this.elem);
        this.rect=parent.getBoundingClientRect();
        Object.assign(this.elem.style,{top:Math.random()*this.rect.height/4+"px",
            left:this.rect.width+"px"// 留神插入开始时是放在视频容器左边外边的
        });
        this.x=this.rect.width;
        this.width=this.elem.offsetWidth;
        TimeManager.instance.add(this);// 当弹幕对象创立好增加到视频容器中之后,再将其增加到观察者的单例对象的 list 上
    }
    update(){if(!this.width) return;
        this.x-=this.speed;
        this.elem.style.left=this.x+"px";
        if (this.x < -this.width) {// 这步是弹幕对象挪动了整个视频容器的地位 + 自身文本撑开的宽度
            // 当弹幕播放完之后删除,观察者单例对象的 list 上,dom 构造中以及堆中都要删除
            TimeManager.instance.remove(this);
            this.elem.remove();
            this.elem=null;
        }
    }
}
正文完
 0