一、HTML页面
在html页面添加回车键的监听,点击了回车则执行bullet中的创建弹幕以及运动操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input{
width: 530px;
height: 40px;
font-size: 30px;
}
.div0{
width:536px;
height: 540px;
position: relative;
overflow: hidden;
}
</style>
</head>
<body>
<div class="div0">
<video src="./test3.mp4" controls></video>
<br>
<input type="text">
</div>
<script type="module">
import Bullet from "./observer/Bullet.js";
var input=document.querySelector("input");
document.addEventListener("keyup",keyHandler);
function keyHandler(e){//回车
if(e.keyCode!==13) return;
if(input.value.trim().length===0) return;
var bullet=new Bullet(input.value);//传入cot,value值
bullet.appendTo(".div0");
input.value="";
}
</script>
</body>
</html>
二、bullet.js
在此js里描述了创建div以及让div横屏运动的操作
import TimeManager from "./TimeManager.js";
export default class Bullet {
rect;
x;
speed = 2;
width;
constructor(txt) {
this.elem = this.createElem(txt);//创建value是输入值的div
}
createElem(txt) {
if (this.elem) return this.elem;
var div = document.createElement("div");
Object.assign(div.style, {
whiteSpace: "nowrap",
position: "absolute",
})
div.textContent = txt
return div;
}
appendTo(parent) {
if (typeof parent === "string") parent = document.querySelector(parent);//输入参数的类型为字符型不是123545
console.log(this);
parent.appendChild(this.elem);//div0节点添加最后一个子节点div
this.rect = parent.getBoundingClientRect();
/* 所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
Object.assign(target, ...sources) 【target:目标对象】,【souce:源对象(可多个)】 */
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;//元素相对父元权素的偏移宽度。等于border+padding+width
TimeManager.instance.add(this);
}
update() {
if (!this.width) return;
this.x -= this.speed;
this.elem.style.left = this.x + "px";
if (this.x < -this.width) {
TimeManager.instance.remove(this);
this.elem.remove();
this.elem = null;
}
}
}
三、TimeManager.js
TimeManager.js里描述了将div弹幕添加到视频上方,以及滚动后删除的操作
export default class TimeManager{
static _instance;
list=new Set();//set存储
ids;
constructor(){
}
static get instance(){//单例模式
if(!TimeManager._instance){
Object.defineProperty(TimeManager,"_instance",{
value:new TimeManager()
})
}
return TimeManager._instance;
}
add(elem){
this.list.add(elem);
if(this.list.size>0 && !this.ids)
this.ids=setInterval(()=>this.update(),16);
}
remove(elem){
this.list.delete(elem);
if(this.list.size===0 && this.ids){
clearInterval(this.ids);
this.ids=undefined;
}
}
update(){
this.list.forEach(item=>{
if(item.update) item.update();
})
}
}