简体   繁体   中英

Animate text in div using css when change

I am changing the innerText of #val, I keep the code as simple as possible

Is there any way to slide in value when text changes?

Edit: I have a container, in this example val and the text inside change base on some conditions, I want to slide in the text when new values applied

 var i = 0; function getValue(){ let mes = ''; if( i %3 == 0) mes= 'This is A' else if(i %3 == 1) mes= 'This is B' else mes= 'this is C' i= i+1; document.getElementById("val").innerText = mes; }
 <input type="button" onclick="getValue()" value="button"> <div id="val"> </div>

I used the animate() method together with the rule of opacity . Gradation animation is quite strict.

Was it necessary?

 var i = 0; function getValue(){ let mes = ''; if( i %3 == 0) mes= 'This is A' else if(i %3 == 1) mes= 'This is B' else mes= 'this is C' i= i+1; document.getElementById("val").innerText = mes; document.getElementById("val").animate([ { transform: 'translateX(-100%)', opacity: '0' }, { transform: 'translateX(-90%)', opacity: '0.1' }, { transform: 'translateX(-80%)', opacity: '0.2' }, { transform: 'translateX(-70%)', opacity: '0.3' }, { transform: 'translateX(-60%)', opacity: '0.4' }, { transform: 'translateX(-50%)', opacity: '0.5' }, { transform: 'translateX(-40%)', opacity: '0.6' }, { transform: 'translateX(-30%)', opacity: '0.7' }, { transform: 'translateX(-20%)', opacity: '0.8' }, { transform: 'translateX(-10%)', opacity: '0.9' }, { transform: 'translateX(0)', opacity: '1' } ], { duration: 500, }); }
 <input type="button" onclick="getValue()" value="button"> <div id="val"> </div>

Second solution, from the category of fadein :

 var i = 0; function getValue(){ let mes = ''; if( i %3 == 0) mes= 'This is A' else if(i %3 == 1) mes= 'This is B' else mes= 'this is C' i= i+1; let opacity = 0.01; let anim_time = setInterval(function() { if(opacity >= 1) { clearInterval(anim_time); } document.getElementById("val").style.opacity = opacity; document.getElementById("val").innerText = mes; opacity += opacity * 0.1; }, 10); }
 <input type="button" onclick="getValue()" value="button"> <div id="val"> </div>

您可以创建另一个函数,其中左对齐在自迭代中与 setTimeout 发生变化,并使 <div id = 'val' onChange = 'function()'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM