<style>
.span {
width: 10em; /*设置显示条长度10em*/
margin-left:20%;
cursor: default;
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
}
</style>
<body>
<div class="span">字体——1——2——滚动——3——4——效果</div>
<script>
var span = document.querySelector('.span');
var timer=null;
let time = 0; //字体滚动长度
function animate(obj) { //字体动画移动函数
var a = obj.innerText.length; //获取div中文本长度
clearInterval(obj.timer);
obj.timer = setInterval(function() {
if (a >= 10) {
time=time-0.1;
obj.style.textIndent = time + 'em';//字体左移0.1个em
// console.log(obj.style.textIndent);
if(time <= -a) {// 如果移动的值大于字体长度
obj.style.textIndent = 10 + 'em'; //文本移动到div右边再向左移
time = 10;
}
}
}, 25);
}
span.onmouseover = function() {
animate(this);
this.style.textOverflow = 'clip'; //字体超出部分剪切
}
span.onmouseleave = function() {
time = 0;//重置字体滚动长度
this.style.textIndent = 0+'em';//字体回到初始位置
clearInterval(this.timer);//停止字体滚动
this.style.textOverflow = 'ellipsis'; //字体超出部分省略
}
</script>
设置25ms的定时器,每25ms字体第一行缩进0.1个单位。若缩进的距离超过了字体长度,字体回到盒子右边,重新缩进。time-0.1,可以将0.1改动,越小,字体滚动越慢越流畅