javascript - 使用 CSS 的逐个字母的文本外观动画

标签 javascript html css animation

我有一个 <div>带文字。

Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

I'd like the text in this <div> to appear on page one character at a time:

L

Lo

Lor

... and so on, until the full text is visible

Acceptable alternative: do that one word at a time, to avoid problems with HTML entities and jumpy words due to soft hyphenation.

If user clicks on the <div>, it should cancel the animation and display the full text instantly.

In short, I want to imitate an animation that is frequently seen in Japanese-style adventure games. (I think that this is sometimes called a typewriter or teletype effect.) Here is a good example:

http://www.youtube.com/watch?feature=player_detailpage&v=SasgN0lim7M#t=418

Obviously, I can script the animation using JavaScript — just set up a timer and append letters (or words) one-by-one.

But is it possible to do what I need with CSS in modern browsers? (Of course, I'd need to at least change element class in the onclick with JS, but that's OK.)

Update: To clarify on characters vs. letters and problems with HTML entities:

My text is littered with the HTML:

Lo&shy;rem <i>ip&shy;sum</i>.

将文本附加到 innerHTML 的天真的方法逐个字符行不通:

L

Lo

Lo&

...Doh!

最佳答案

您可以使用一些 jQuery 来实现这一点。

查看我的 fiddle :http://jsfiddle.net/kA8G8/7/

HTML

<p class="typewriter">Nullam id dolor id nibh ultricies vehicula ut id elit. Maecenas faucibus mollis interdum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras justo odio, dapibus ac facilisis in, egestas eget quam.</p>

JS

var text = $('.typewriter').text();

var length = text.length;
var timeOut;
var character = 0;


(function typeWriter() { 
    timeOut = setTimeout(function() {
        character++;
        var type = text.substring(0, character);
        $('.typewriter').text(type);
        typeWriter();

        if (character == length) {
            clearTimeout(timeOut);
        }

    }, 150);
}());

关于javascript - 使用 CSS 的逐个字母的文本外观动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767069/

相关文章:

javascript - jQuery isotope - 在 Firefox 中点击嵌入的 youtube 视频时页面跳转到顶部

css - 如何为嵌套元素设置 Z-index?

javascript - 我的脚本中的 "this"对象不支持 IE 中的此属性或方法

html - CSS - 100% 宽度的输入与 div 重叠

javascript - 如何判断父元素的开头或结尾是否存在文本? HTML DOM 和 JavaScript

css - 在具有动态宽度的居中 div 内具有 100% 宽度的 Div?

javascript - IE8中的CSS问题

javascript - Fineuploader 未设置 x-amz-credentials

JavaScript 事件 : Getting notified of changes in an &lt;input&gt; control value

javascript - 将每篇文章与相关信息相关联