问题
I am trying to provide a simple way to get a typing text effect, but with the possibility to allow HTML tags too. I have some code that works, but I see the tags are being considered part of the text.
For example, if The text is "Anyone is <b>awesome</b>
, I see the following when it reaches the bold part:
<
<b
<b>
<b>a
<b>aw
<b>awe
<b>awes
<b>aweso
<b>awesom
<b>awesome
<b>awesome<
<b>awesome</
<b>awesome</b
<b>awesome</b>
How can I skip html nodes without removing them from string? I want to keep the formatting working.
Here's what I've done so far:
<div id="foo"></div>
$.fn.typer = function (text, options) {
options = $.extend({}, {
delay: 1000,
duration: 1000,
easing: 'linear',
endless: false
}, options);
var elem = $(this);
(function loop(i) {
var e = typeof text === 'string' ? text : text[i];
// strip html tags, might be helpful
// e.replace(/(<.*?>)/ig,"")
$({len: 0}).delay(options.delay).animate({len: e.length}, {
duration: options.duration,
easing: options.easing,
step: function (now) {
var pos = Math.ceil(now),
char = e.substr(pos, 0);
elem.html(e.substr(0, pos));
},
complete: function () {
i++;
if (i === text.length && !options.endless) {
return;
} else if (i === text.length) {
i = 0;
}
loop(i);
}
});
})(0);
};
$('#foo').typer(['<i>Anyone</i> <u>is</u> <b>awesome</>!', 'Foo bar.']);
Working demo:
http://jsfiddle.net/ARTsinn/RED9H/2/
Update
Got it!
example without jQuery
's animate-function.
If you've any improvements, share them here!
回答1:
To strip the tags from e
, use:
e = $(e).text();
This assumes e is known to contain HTML to begin with. If it might contain plain text, wrap it in a DIV first:
e = $('<div>'+e+'</div>').text();
Otherwise, jQuery will try to interpret it as a selector.
回答2:
Sort of like what “Let me Bing that for you!” does? Example
The Javascript that does the typing effect can be downloaded - but check the license terms first. http://letmebingthatforyou.com/scripts/lmbtfy.js seems to be doing most of the work.
来源:https://stackoverflow.com/questions/14714162/typing-text-effect-with-formatting-skip-html-tags-but-dont-remove