html部分
<title>文字滚动</title>
<link rel="stylesheet" href="./index.css" />
<!-- defer 推迟 -->
<!-- <script src="./index.js" defer></script> -->
<script src="./index.js" defer></script>
</head>
<body>
<div class="center">
<h1 class="title">最新公告</h1>
<ul class="list">
<li>1.Lorem ipsum dolor sit.</li>
<li>2.Repellat quis ipsam quisquam.</li>
<li>3.Laudantium hic saepe blanditiis!</li>
<li>4.Facere rerum animi totam?</li>
</ul>
</div>
</body>
css部分
*{
padding: 0;
margin: 0;
list-style: none;
box-sizing: border-box;
}
.center{
background: tomato;
overflow: hidden;
padding:20px 0;//BFC
}
.title{
float: left;
font-size: 16px;
font-weight: normal;
margin-top: 4px;
margin-left: 20px;
border-right: 3px solid #ccc;
width:100px;
}
.list{
float: left;
height:30px;
overflow: hidden;
margin-left: 60px;
}
.list li{
height: 30px;
line-height: 30px;
}
js部分
(function () {
//元素获取集合
var list = document.querySelector(".list");
var center = document.querySelector(".center");
//1.初始化
function init() {
//ul下的第一个li克隆,cloneNode(true)深度克隆,包含内容
var li = list.children[0].cloneNode(true);
list.appendChild(li);
}
init();//自调用
//2.滚动: 就是给scrollTop赋值
var duration = 2000;//声明变量储存计时器的时间
var height = 30;//每个li的固定高度
setInterval(moveNext, duration);//创建定时器,这边为了方便管理函数写在外面,这里调用函数名
//3.定时器函数
var curIndex = 0;//声明每一项的位置,0->0,1->30,2->60
function moveNext() {
var from = curIndex * height;//滚动开始的位置,第一项*高度
chengeBg();//随机改变颜色函数
curIndex++;//位置下标自增
var to = curIndex * height;//结束位置,等于最后一项*高度
//4.动画效果,就是定时器实现
//规定多长时间,间隔多久,每次变化多少,需要多少次完成变化
var timeAll = 300;//变化总时间
var dur = 15;//变化间隔时间
var times = timeAll / dur;//变化需要的次数
var dis = (to - from) / times;//每次变化改变多少
//创建定时器
var timesId = setInterval(function () {
from += dis;//最开始累加每次变化多少
if (from >= to) {//如果开始>结束,清除定时器
clearInterval(timesId);
}
if (curIndex === list.children.length - 1) {//如果结束的下标===ul下li长度-1的下标时,设置开始位置和当前下标为0
from = 0;
curIndex = 0;
}
}, dur);//dur就是定时器的间隔时间
list.scrollTop = from;//最后把开始的位置赋值给滚动的高度
}
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function chengeBg() {
list.style.background =
"rgb(" +
getRandom(0, 256) +
"," +
getRandom(0, 256) +
"," +
getRandom(0, 256) +
")";
center.style.color =
"rgb(" +
getRandom(0, 256) +
"," +
getRandom(0, 256) +
"," +
getRandom(0, 256) +
")";
center.style.background =
"rgb(" +
getRandom(0, 256) +
"," +
getRandom(0, 256) +
"," +
getRandom(0, 256) +
")";
}
})();