手机屏幕弹幕纵向滚动,添加弹幕实时滚动
transform 可在不改变页面dom结构的前提下进行实时动画,比传统的通过top的高度来做动画性能要高出很多。
requestAnimationFrame 链接 推荐用此做动画,比传统setInterval渲染性能更强。
- 滚动原理就是设置一个固定位置
position:relative
的父盒子,子盒子相对父盒子,溢出部分隐藏掉。方法一、通过改变子盒子的top高度来进行滚动。方法二、通过transform
改变其纵坐标偏移即可实现滚动(推荐) - 根据原生js自己改成相对于的vue和react写法
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
height: 190px;
width: 50%;
position: relative;
border: 1px solid red;
overflow: hidden;
}
.box-ul {
position: absolute;
left: 0;
top: 0;
overflow: hidden;
}
.ul-li {
height: 40px;
background: pink;
margin: 4px;
}
</style>
</head>
<body>
<button onclick="addMessage()">添加弹幕</button>
<div class="box" id="box">
<ul class="box-ul" id="ul">
<li class="ul-li">11111111</li>
<li class="ul-li">22222222</li>
<li class="ul-li">33333333</li>
<li class="ul-li">44444444</li>
<li class="ul-li">555555555</li>
<li class="ul-li">6</li>
<li class="ul-li">7</li>
<li class="ul-li">8</li>
<li class="ul-li">9</li>
</ul>
</div>
<script>
const box = document.getElementById("box");
const ul = document.getElementById("ul");
let posY = 0;
let boxHeight = box.clientHeight;//可见高度 190
let ulHeight = ul.offsetHeight; //实际高度 400
// stop move Height -210 = 190-400
// console.log(ulHeight);
let reqFrame = ''
window.onload = function () {
console.log("window onload");
reqFrame = requestAnimationFrame(step);
}
function addMessage() {
const li = document.createElement("li");
li.textContent = "添加";
li.className = "ul-li"
ul.appendChild(li);
ulHeight = ul.offsetHeight;
step()
}
function step() {
if (posY < (boxHeight - ulHeight)) {
cancelAnimationFrame(reqFrame)
} else {
posY -= 1;
requestAnimationFrame(step);
ul.style.transform = `translateY(${posY}px)`;
}
}
</script>
</body>
</html>