index.htm
<!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>文字滚动效果</title>
<link rel="stylesheet" href="index.css">
<script src="index.js" defer></script>
</head>
<body>
<div class="container">
<h1 class="title">最新公告</h1>
<ul class="list">
<li>1.Lorem ipsum dolor sit.</li>
<li>2.Natus repudiandae velit soluta.</li>
<li>3.Eveniet modi velit aliquid.</li>
<li>4.Eligendi fugiat doloribus fuga.</li>
</ul>
</div>
</body>
</html>
index.css
.container{
background-color: #bfedfc;
overflow: hidden;
padding: 20px 0;
}
.title{
float: left;
font-size: 16px;
font-weight: normal;
margin: 0;
margin-left: 20px;
line-height: 30px;
border-right: 2px solid #ccc;
padding-right: 30px;
}
.list{
float: left;
list-style: none;
padding: 0;
height: 30px;
overflow: hidden;
margin: 0;
margin-left: 50px;
}
.list li{
height: 30px;
line-height: 30px;
}
index.js
var list = document.querySelector('.list');
function cloneFirstItem() {
var firstItem = list.children[0];
var newItem = firstItem.cloneNode(true);
list.appendChild(newItem);
}
cloneFirstItem();
var duration = 2000;
setInterval(moveNext, duration);
var curIndex = 0;
var itemHeight = 30;
function moveNext() {
var from = curIndex * itemHeight;
curIndex++;
var to = curIndex * itemHeight;
var totalDuration = 300;
var duration = 10;
var times = totalDuration / duration;
var dis = (to - from) / times;
var timerId = setInterval(function () {
from += dis;
if(from >= to){
clearInterval(timerId);
if(curIndex === list.children.length - 1){
from = 0;
curIndex = 0;
}
}
list.scrollTop = from;
}, duration);
}