Typing text effect with formatting: skip HTML tags, but don't remove

回眸只為那壹抹淺笑 提交于 2019-12-24 08:48:55

问题


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

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