一、实现效果
二、源码
<!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>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.wrapper {
width: 60%;
height: 30px;
background-color: #000;
overflow: hidden;
position: relative;
}
.text {
color: #fff;
white-space: nowrap;
line-height: 30px;
position: absolute;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="text">海外徒闻更九州,他生未卜此生休。 空闻虎旅传宵柝,无复鸡人报晓筹。 此日六军同驻马,当时七夕笑牵牛。 如何四纪为天子,不及卢家有莫愁。</div>
</div>
<script>
const wrapper = document.getElementsByClassName("wrapper")[0] // 容器
const text = document.getElementsByClassName("text")[0] // 文本
const wrapperWidth = wrapper.clientWidth // 容器的总宽度
const textWidth = text.clientWidth // 文本的总宽度
let textRun = null // 循环器
text.style.left = wrapperWidth + "px" // 开始滚动前设定文本在容器最右侧以外
textRoll()
// 开始滚动
function textRoll() {
let textLeft = text.style.left.split("px")[0] // 获取文本的left值
textRun = setInterval(() => { // 设定循环器,通过left滚动文本
textLeft -= 1
text.style.left = textLeft + "px"
if (textLeft == -textWidth) { // 当到达文本最大宽度(播放完文本)
clearInterval(textRun)
setTimeout(() => { // 间隔1.5s后再次执行文本滚动
text.style.left = wrapperWidth + "px"
textRoll()
}, 1500);
}
}, 10);
}
// 鼠标 移入/移出 时 停止/开始 滚动
wrapper.onmouseover = function() {
clearInterval(textRun)
}
wrapper.onmouseout = function() {
textRoll()
}
</script>
</body>
</html>