jQuery: Animate on change of .innerHTML or .text

泄露秘密 提交于 2021-02-07 20:01:26

问题


I'm translating my site by dynamically changing the text on the website with jQuery like this:

<span id="mySpan">Something in English</span>

$('#mySpan').html("Something else in Spanish");

It works great but, due to changes in the length of the text, it's a hard transition, the new text just appears and parent element is resizing instantly.

Is there an easy way to animate/ease the transition during the change of text? Like Fadeing and/or resizing nicely?

I know it's possible with hidden elements, but because I have lot's of text, I don't want to load this if not needed.

Thanks!


回答1:


Well, if your span element has a parent, e.g.:

<div class="parent">
    <span id="mySpan">Something in English</span>
</div>

you could do it like this:

$('#mySpan').animate({'opacity': 0}, 400, function(){
        $(this).html('Something in Spanish').animate({'opacity': 1}, 400);    
    });

Basically, you animate child span's opacity to 0, 400 is transition time in ms. After that action is done, you do a callback function which replaces span's html with wanted text while it still has opacity: 0, and then you do backwards animation to opacity: 1.

Live example



来源:https://stackoverflow.com/questions/26429480/jquery-animate-on-change-of-innerhtml-or-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!