react 使用定时器写单行文字左右滚动效果

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!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值