使用JavaScript的HTML打字机效果 [英] Typewriter-Effect for HTML with JavaScript

查看:103
本文介绍了使用JavaScript的HTML打字机效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做到以下几点:我想在HTML / JavaScript中有打字机效果(如果需要,可以使用jQuery / jQuery UI)。关于如何在字符串上创建打字机效果,有很多很棒的例子(例如这个)。我想要做类似的事情,但要使用完整的HTML字符串,不应该将其输入,而应该正确插入到网页中。



示例字符串:

 < p>这是我的< span style ='color:red;'>特殊字符串< / span>用< img src =test.png/>图片!< / p> 

该字符串应该用打字机动画输入。即使在打字时,特殊字符串的颜色也应该是红色的,并且图像应该出现在an一词之后和image一词之前。解决方案的问题在于它们将标记字符逐个插入到网页中,导致在此示例中键入特殊字符串时未封闭。我考虑使用jQuery解析字符串并迭代数组,但我不知道如何处理嵌套标记(如本例中的p和span)

解决方案

我认为你并不需要一个插件来做这件事,我做了一个简单的例子:

html:

 < div id =typewriter>< / div> 

js:

  var str =< p>这是我的< span style ='color:red;'>特殊字符串< / span>,其中< img src ='http://placehold.it / 150x150'>图片!< / p>,
i = 0,
isTag,
text;

(函数type(){
text = str.slice(0,++ i);
if(text === str)return;

document.getElementById('typewriter')。innerHTML = text;

var char = text.slice(-1);
if(char ==='<') isTag = true;
if(is ==='>')isTag = false;
$ b $ if(isTag)return type();
setTimeout(type,80) ;
}());

以下是 jsfiddle


I want to do the following: I want to have a typewriter effect in HTML/JavaScript (jQuery/jQuery UI, if needed). There are tons of great examples out there on how to create a typewriter effect on a string (for example this one). I want to do something similar, but with a complete HTML string, which shouldn't be typed out, but inserted properly into the web page.

Example string:

<p>This is my <span style='color:red;'>special string</span> with an <img src="test.png"/> image !</p>

This string should be typed with a typewriter animation. The color of "special string" should be red, even while typing, and the image should appear after the word "an" and before the word "image". The problem with the solutions out there is that they insert the markup character by character into the web page, which results in an unclosed while typing the "special string" in this example. I considered parsing the string with jQuery and iterating over the array, but I have no idea how I would deal with nested tags (like p and span in this example)

解决方案

I think you don't really need a plugin to do this stuff, I made a simple example:

html:

 <div id="typewriter"></div>

js:

var str = "<p>This is my <span style='color:red;'>special string</span> with an <img src='http://placehold.it/150x150'> image !</p>",
    i = 0,
    isTag,
    text;

(function type() {
    text = str.slice(0, ++i);
    if (text === str) return;

    document.getElementById('typewriter').innerHTML = text;

    var char = text.slice(-1);
    if( char === '<' ) isTag = true;
    if( char === '>' ) isTag = false;

    if (isTag) return type();
    setTimeout(type, 80);
}());

And here is the demo on jsfiddle

这篇关于使用JavaScript的HTML打字机效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆