这是一个比较简单的小案例,就是文字上下滚动出来。下面就是源代码,希望大佬指正!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文字滚动效果</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.scrool-text {
width: 450px;
padding: 15px;
margin: 20px;
background-color: #e3fdfd;
border-radius: 8px;
height: 50px;
display: flex;
justify-content: space-between;
align-items: center;
}
.scrool-text .title {
height: 20px;
padding-right: 10px;
border-right: 2px solid #ccc;
}
.scrool-text .content ul {
overflow: hidden;
height: 50px;
line-height: 50px;
}
</style>
</head>
<body>
<div class="scrool-text">
<div class="title">最新公告</div>
<div class="content">
<ul class="list">
<li>1. Lorem ipsum dolor sit amet.</li>
<li>2. Amet hic ipsum offices vitae!</li>
<li>3. Debits quart qua sapient venial.</li>
<li>4. Ilium nobs object oddity sapient?</li>
<li>5. Et laudanum nemo official omnibus.</li>
</ul>
</div>
</div>
</body>
<script>
//首先要确保中间有缓冲的时间,因此需要复制第一个li到最后一个
let list = document.querySelector('.list')
// function copy() {
// // 复制第一个li到最后一个
// let newItem = list.children[0].cloneNode(true)
// list.appendChild(newItem)
// }
// copy()
let duration = 1500 // 滚动持续时间
const itemHeight = 50 // 每个li的高度
let currendIndex = 0 //目前展示的是第几位元素
function moveNext() {
currendIndex++
if (currendIndex == list.children.length) {
currendIndex = 0
}
list.scrollTop({
top: currendIndex * itemHeight,
behavior: 'smooth'
})
}
setInterval(moveNext, duration)
</script>
</html>