13-传统弹幕
程序员文章站
2022-04-21 10:14:31
传统弹幕简述:实现最简单的弹幕html部分 Document
传统弹幕
简述:实现最简单的弹幕
dom简单实现传统弹幕
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="txt" id="txt">
<button id="btn">提交</button>
</body>
</html>
js部分
<script>
var btn = document.getElementById("btn");
btn.onclick = function(){
// clearInterval(timer);
var txt = document.getElementById("txt").value;
var span = document.createElement("span");
span.innerHTML = txt;
//清空之前的样式
document.getElementById("txt").value="";
//js操作span的行内样式
span.style.position = "absolute";
span.style.left = "600px";
span.style.top = Math.floor(document.documentElement.clientHeight * Math.random()) + "px";
//将span挂载到DOM上
document.body.appendChild(span);
var timer = setInterval(function (){
span.style.left = parseInt(span.style.left) - 4 + "px";
//当span离开浏览器,需要清空定时器,并销毁span
if(parseInt(span.style.left) < -1 * span.offsetWidth)
{
//删除span
document.body.removeChild(span);
//清空定时器
clearInterval(timer);
console.log(timer);
}
},40)
}
</script>
运行效果
面向对象实现传统弹幕
其他部分如上,只有js发生改变
<script>
// DOM JQ
function Bullet(words) {
this.span = document.createElement("span");
if(Math.random()<0.2){
this.span.style.fontSize = "50px";
}
this.span.style.position = "absolute";
this.span.style.left = document.body.offsetWidth + "px";
console.log(document.documentElement.offsetHeight)
this.span.style.top = Math.floor(document.body.offsetHeight*Math.random()) + "px";
this.span.innerHTML = words;
this.timer = null;
this.init(); // 初始化工作
this.move(); // 滚动起来
}
Bullet.prototype.init = function () {
document.body.appendChild(this.span)
}
Bullet.prototype.move = function () {
let that = this;
this.timer = setInterval(function () {
// 改变弹幕的left
that.span.style.left = parseInt(that.span.style.left) - 4 + "px";
if(parseInt(that.span.style.left) < -1*this.span.offsetWidth){
// 删除span
document.body.removeChild(that.span)
// 清除定时器
clearInterval(that.timer)
}
},50)
}
var btn = document.getElementById("btn");
btn.onclick = function () {
let words = document.getElementById("words").value;
let obj = new Bullet(words);
}
</script>
本文地址:https://blog.csdn.net/weixin_45344023/article/details/107881964
下一篇: 【NOIP2012模拟8.7】奶牛编号