ps: 效果图现在不上了,等以后再上吧;类似于游戏中滚动的公告!
自己研究的!
html部分
<div className="textFather" ref="textFather">
<div className="text" ref="text">
<span>{"我是后台传过来的未知字数的数据"}</span>
</div>
</div>
css部分
.textFather{
width:1000px;
height:40px;
position:relative;
overflow:hidder;
}
.text{
position:absolute;
top:0;
left:0;
height:100%;
line-height:40px;
text-overflow:ellipsis;
white-space:nowrap;
}
css部分要注意的是子盒子的text-overflow:ellipsis、white-space:nowrap;这个2个属性,文本强制不换行,要不很麻烦的,一行,我认为想来来说好计算;
js部分
textLeftToRight=()=>{
let num =0;
const text=this.refs.text; // 获取文字
const textFather=this.refs.textFather;
if(text.offsetWidth>textFather.offsetWidth){ // 当文字长度大于父盒子长度时;才会滚动;
if(text.offsetWidth===-num){
num=text.offsetWidth; // 让值变为父盒子的宽度;
clearInterval(timer1); // 清楚定时器;
}else{
num--;
text.style.left=`${num}px`;
if(text.offsetWidth-(text.offsetWidth-parseInt(textFather.offsetWidth/2)===-num){ // text 滚动到一定距离时;
const text2=text.cloneNode(true); // 克隆text;
textFather.appendChild(text2).classList.add("text2"); // 父盒子添加克隆的元素并添加class类名;
let num2=textFather.offsetWidth; // 设置text2默认出现位置;
this.timer2=setInterval(()=>{
if(text2.offsetWidth===-num2){
num2=textFather.offsetWidth; // 设置默认值;
text.cloneNode(false); // 取消克隆;
textFather.removeChild(text2); // 父盒子删除之前克隆的子盒子;
clearInterval(timer2); //清楚这个定时器;
}
num2--;
text2.style.left=`${num2}px`;
if(text2.offsetWidth-(text.offsetWidth-parseInt(textFather.offsetWidth/2))===-num2){
this.timer1=setInterval(()=>this.textLeftToRight(),30) // 从新调用定时器1;
}
},30)
}
}
}
}
componentDidMount(){
this.timer1=setInterval(()=>this.textLeftToRight(),30); // 调用;
}
componentWillUnmount(){
clearInterval(this.timer1);
clearInterval(this.timer2);
}
Js部分,我也有过在将timer2定时器单独封装一个函数,但不知啥问题,num2–;不执行,导致效果出不来,以后研究!
ps: 记录+研究,定时器是主要,老忘记定时器的使用跟清楚;setTimeout还在研究,单个滚动很好实现,就几行代码,多个+重复调用没整明白!囧o(╯□╰)o!!!