Html5+css3+js完成无缝跑马灯效果
HTML 部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="index.css">
<style>
* {
margin: 0px;
padding: 0px;
}
#a1,
#a2 {
width: 300px;
height: 300px;
overflow: hidden;
white-space: nowrap;
}
#a1 p,
#a2 p {
float: left;
height: 30px;
line-height: 30px;
}
</style>
</head>
<body>
<div id="a1">
<p>欢迎您,只有努力奋斗</p>
<p>欢迎您,只有努力奋斗才会有美好的未来,哈哈哈哈。</p>
<p>欢迎您,只有努力奋斗才会有美好的未来,哈啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊哈哈哈。</p>
</div>
<div id="a2">
</div>
</body>
<script src="index.js"></script>
<script>
var arrs = ["大神困了就大神了啊啊啊啊啊啊啊啊。", "吖,那大家的撒娇单独,萨达撒旦教啊--", "奥斯卡级大烧烤加--", "卡机的撒娇的萨达哈。卡介绍的---"]
for (let i = 0; i < arrs.length; i++) {
document.querySelector("#a2").innerHTML += `
<p>${arrs[i]}</p>
`
}
document.querySelectorAll("#a2 p").forEach(function (item) {
Roll(item)
})
var arr = document.querySelectorAll("#a1 p");
for (let i = 0; i < arr.length; i++) {
Roll(arr[i]);
};
</script>
</html>
Css部分
.marquee-left {
float: left;
height: 30px;
will-change: transform;
will-change: -webkit-transform;
line-height: 30px;
}
@-webkit-keyframes marquee-left-animate {
0% {
-webkit-transform: translate3d(0, 0, 0);
}
100% {
-webkit-transform: translate3d(-50%, 0, 0);
}
}
Js部分
//divId必须为dom元素
function Roll(divId) {
var str = divId.innerHTML
var time = (leng(str)) / 6 + "s"
//中文字符为2个长度,英文为1个,按需判断
if (leng(str) > 30) divId.style.cssText = "overflow: hidden; text-overflow: ellipsis;white-space: nowrap; width: 240px;"
else return
divId.onmouseenter = function () {
divId.innerHTML = `<div class="marquee-left" style="animation:marquee-left-animate ${time} linear infinite;"><span>${str}</span><span>${str}</span></div>`
}
divId.onmouseleave = function () {
divId.innerHTML = str;
}
}
function leng (str) {
return str.replace(/[\u0391-\uFFE5]/g, "aa").length; //先把中文替换成两个字节的英文,在计算长度
};