需求:
1.页面上漂浮字体大小不一、颜色不一,从左向右滚动的弹幕;
2.底部中间有一个发送功能,可以发送新的弹幕;
3.底部的发送部分可以向下收起和弹出。
原理:
创建两个数组分别装文字颜色和大小,将上面box里放入input输入的内容,用span标签包裹,利用定时器实现文字从左向右滚动,每隔一段时间向右移动一段距离,如果弹幕滑到可视区域以外就被销毁
效果图:
滚动弹幕
代码块:
<style>
*{
margin: 0;
padding: 0;
text-decoration: none;
}
.top{
position: relative;
height: 600px;
border-bottom: 1px solid #ccc;
background-color: #ccc;
}
.bottom{
display: block;
width: 100%;
height: 240px;
background-color: rgb(240, 221, 224);
}
.a1{
display: block;
position: absolute;
left: 0;
bottom: 0px;
width: 40px;
height: 40px;
font-size: 14px;
background-color: rgb(250, 171, 171);
text-align: center;
color: black;
line-height: 40px;
border-radius: 50%;
}
.a2{
display: block;
position: absolute;
left: 0;
bottom: 45px;
width: 40px;
height: 40px;
font-size: 14px;
background-color: rgb(245, 206, 239);
text-align: center;
color: black;
line-height: 40px;
border-radius: 50%;
}
span{
display: inline-block;
position: absolute;
left: 0;
}
input{
margin-left: 530px;
margin-top: 40px;
width: 300px;
height: 25px;
border:2px solid pink;
background-color: rgb(252, 244, 244);
padding-left: 15px;
border-radius: 15px;
}
button{
width: 55px;
height: 25px;
border-radius: 15px;
border:2px solid pink;
background-color: rgb(244, 157, 157);
}
</style>
<body>
<div class="top">
</div>
<div class="bottom">
<input type="text" placeholder="快来发送一条弹幕吧~">
<button>发送</button>
</div>
<a href="#" class="a1">收起</a>
<a href="#" class="a2">弹出</a>
</body>
window.onload=function(){
// 创建两个数组分别装文字颜色和大小
var Color = ["red","yellow","blue","green","pink","black","aqua","peru","salmon","purple"]
var Size = ["14px","16px","18px","25px","20px","22px"]
// 获取按钮,点击按钮发送弹幕
var btn = document.querySelector("button")
var top = document.querySelector(".top")
var input = document.querySelector("input")
btn.onclick=function(){
// 将上面box里放入input输入的内容,用span标签包裹
var span = document.createElement("span")
top.appendChild(span)
span.innerHTML=input.value
// 给这个标签一个随机高度和颜色还有大小
span.style.fontSize = Size[Math.round(Math.random()*7)]
span.style.color = Color[Math.round(Math.random()*11)]
span.style.top = Math.round(Math.random()*500)+"px"
// 实现文字从左向右滚动,利用定时器,每隔一段时间向右移动一段距离
var step = 0
var timer = setInterval(() => {
step++
span.style.left =step+"px"
// 如果弹幕滑倒可视区域以外就被销毁
var move = span.offsetLeft+span.clientWidth
if(move-window.innerWidth==20){
clearInterval(timer)
top.removeChild(span)
}
}, 25);
}
btn.onmouseleave=function(){
input.value=""
}
var a1 = document.querySelector(".a1")
a1.onclick=function(){
var bottom = document.querySelector(".bottom")
// bottom.style.display = "none"
bottom.style.height=90+"px"
top.style.height=750+"px"
}
var a2 = document.querySelector(".a2")
a2.onclick=function(){
var bottom = document.querySelector(".bottom")
// bottom.style.display = "none"
bottom.style.height=240+"px"
top.style.height=600+"px"
}
}