我有一个 <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­rem <i>ip­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/