一、弹幕效果要求
1.页面上漂浮字体大小不一、颜色不一,从左向右滚动的弹幕;
2.底部中间有一个发送功能,可以发送新的弹幕;
3底部的发送部分可以向下收起和弹出。
二、实验原理
- 首先利用利用点击事件使得提交与书写台隐藏于显示加载出来
- 利用时间间隔将所写的弹幕由左向右来回运动
- 再利用Math.random获取随机数,来达到改变字体大小和颜色
三、实验效果
弹幕效果
四、代码
<!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>
*{
padding: 0%;
margin: 0%;
}
body{
background-color: #414141;
width: 1920px;
}
#box{
position:absolute;
bottom: 200px;
left: 43%;
}
#box input{
display: none;
}
#box input:first-child{
width: 400px;
height: 50px;
border-radius: 20px;
outline: none;
font-size: 25px;
}
#box input:nth-child(2){
width: 60px;
height: 60px;
border-radius: 50%;
cursor: pointer;
font-size: 20px;
position: relative;
}
#box input:nth-child(2):hover{
background-color: rgba(128, 128, 128, 0);
color: red;
}
.btn{
width: 50px;
height: 50px;
background-color: gray;
text-align: center;
line-height: 50px ;
position: relative;
left: 167px;
cursor: pointer;
opacity: 50%;
}
.btn:hover{
background-color: black;
}
.btnB{
display: none;
}
.btnT{
bottom: 100px;
}
</style>
</head>
<body>
<div id="box">
<input type="text" id="text">
<input type="submit" id="sub">
<div class="btnT btn">
<img src="../寒假小练习/images/向下箭头 (1).png" width="35px" height="35px" alt="">
</div>
<div class="btnB btn">
<img src="./向上箭头.png" width="35px" height="35px" alt="">
</div>
</div>
<script>
var btnT = document.querySelector(".btnT")
var btnB = document.querySelector(".btnB")
var text = document.getElementById("text")
var sub = document.getElementById("sub")
//当点击按键的时候就显示/隐藏input按钮
btnT.onclick = function(){
btnB.style.display = "block"
btnT.style.display = "none"
text.style.display = "block"
sub.style.display = "block"
sub.style.left = "160px"
}
btnB.onclick = function(){
btnT.style.display = "block"
btnB.style.display = "none"
text.style.display = "none"
sub.style.display = "none"
}
sub.onclick = function(){
changes()
}
//随机给数加颜色
function colors(div){
let arr=[]
let arr1 = []
for(var i = 0 ; i< 3 ;i++){
var number = Math.floor(Math.random()*255)
arr.push(number)
}
div.style.color = `rgb(${arr[0]},${arr[1]},${arr[2]})`
}
//设置其弹幕所开始的位置
function changes() {
var div = document.createElement("div")
div.className = "newDiv"
div.innerHTML = text.value
//让其在页面显示
document.body.append(div)
div.style.position = "absolute"
//获取其在顶部的位置,随机加上一个数改变其的初始位置
changeHeight = Math.floor(Math.random()*1000)
div.style.top = changeHeight + "px"
text.value = ''
colors(div)
var word = Math.floor(Math.random()*80+20)
div.style.fontSize = word + "px"
//设置让其滚动
setInterval(function(){
var lefts = parseInt(div.offsetLeft)
var rights = parseInt(getComputedStyle(div).right)
div.style.right = rights + 20 +"px"
if(lefts <= 0){
div.style.right = 0
}
},15)
}
window.onkeydown = function(e){
if(e.keyCode == 13){
changes()
}
}
</script>
</body>
</html>