要求:1.页面上漂浮字体大小不一、颜色不一,从左向右滚动的弹幕;
2.底部中间有一个发送功能,可以发送新的弹幕;
3.底部的发送部分可以向下收起和弹出。
原理:弹幕的移动:通过定时器
首先定义一个数组用于存储颜色 字体,与距离顶部的距离,将所有的p标签设置为绝对定位来修改高度不同,实现漂浮的弹幕只需要预先设置好几个p标签,通过for循环与随机的函数将其赋予不同的颜色 字体 高度,当距离左边距一定距离的时候删除自己这个元素并清除定时器
发送功能点击后会通过父节点创建一个子节点并获取到输入的值将其放入html中,同样的为他其赋予不同的颜色 字体 高度,并设置定时器,当他距离左端一定距离时将改子节点删除。
收起和弹出:通过收起按钮,收起的时候表现形式为none
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
text-decoration: none;
list-style: none;
}
#bigbox {
height: 1010px;
width: 100%;
background-color: rgb(204, 250, 252);
}
#send {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100px;
border: 3px solid red;
}
#send button {
margin-left: 5px;
}
#zhedie {
position: absolute;
left: 1150px;
bottom: 46px;
opacity: 50%;
}
#bigbox p {
position: absolute;
}
</style>
</head>
<body>
<div id="bigbox">
<p class="yuxian">6666666666666</p>
<p class="yuxian">333333333333333</p>
<p class="yuxian">111111111</p>
<p class="yuxian">高能预警高能预警</p>
</div>
<div id="send">
<input type="text" placeholder="在此处发送你的弹幕" id="textdanmu">
<button id="fasong">发送</button>
</div>
<button id="zhedie">折叠</button>
<script>
var color = ["red", "bule", "cyan", "coral", "cornflowerblue", "darkblue", "cornsilk", "darkcyan", "darkgoldenrod", "darkgray", "black", "aqua", "peru", "salmon"]
var size = ["21px", "22px", "25px", "20px", "23px"]
yuxian = document.querySelectorAll(".yuxian")
var step = 0
for (i = 0; i < yuxian.length; i++) {
yuxian[i].style.fontSize = size[Math.floor(Math.random() * 6)]
yuxian[i].style.color = color[Math.floor(Math.random() * 14)]
yuxian[i].style.top = Math.random() * 900 + "px"
}
var time1 = setInterval(function () {
step = step + 50
for (m = 0; m < yuxian.length; m++) {
yuxian[m].style.left = step + 'px'
if (yuxian[m].offsetLeft >= 2000) {
yuxian[m].remove()
}
}
}, 300)
zhedie.onclick = function () {
if (send.style.display == "flex") {
send.style.display = "none"
} else { send.style.display = "flex" }
}
fasong.onclick = function () {
var fasongde = textdanmu.value
var newp = document.createElement("p")
bigbox.appendChild(newp)
newp.innerHTML = fasongde
newp.style.fontSize = size[Math.floor(Math.random() * 6)]
newp.style.color = color[Math.floor(Math.random() * 14)]
newp.style.top = Math.random() * 900 + "px"
var speed = 0
var timer = setInterval(function () {
speed = speed + 60
newp.style.left = speed + 'px'
console.log(newp.offsetLeft)
if (newp.offsetLeft >= 2000) {
clearInterval(timer)
bigbox.removeChild(newp)
}
}, 300)
textdanmu.value = ""
}
</script>
</body>
</html>