简体   繁体   English

如何在 JavaScript 中创建将考虑 html 标签规则的打字机效果?

[英]How to create a typewriter effect in JavaScript THAT will take into account html tag rules?

Suppose I had some text from a div tag like this:假设我有一些来自 div 标签的文本,如下所示:

 <div id="outPutContainer">
     <div id="contentDiv" style="display:none;"> This is some cool content... </div>
 </div>

Now if I wanted to, I could create a JavaScript function that will print the characters one at a time and it will work just fine.现在,如果我愿意,我可以创建一个 JavaScript 函数,该函数将一次打印一个字符,并且可以正常工作。 Example below.下面举例。

function printSentence(inner, outer, index, speed) {
    var input = document.getElementById(inner).innerHTML;
    var timer = setInterval(function(){
        document.getElementById(outer).innerHTML+=input.charAt(index);
        index++;
        if(index  == sentence.length -1){
            printResume(inner, outer, index+1, speed);
        }else{
           clearInterval(timer);
        }
     }, speed);
}

printSentence("contentDiv", "outPutContainer", 0, 100);

Again, the above function works just fine, however let's say I wanted to take into account html tags within the element, how would that work.同样,上面的函数工作得很好,但是假设我想考虑元素中的 html 标签,这将如何工作。 An example would be一个例子是

<div id="contentDiv2"> This is some cool <strong>content</strong>
    <p>Paragraph of content</p>
</div>

So the ideal effect would be所以理想的效果是

This is some cool content这是一些很酷的内容

Paragraph of content内容段落

(The typewriter effect was inspired by Charlie) "I like to give credit where credit is due" (: Javascript typing effect (打字机效果的灵感来自查理)“我喜欢在信用到期的地方给予信用”(: Javascript 打字效果

I suppose I can throw in a jsFiddle to make easier on folks.我想我可以加入一个 jsFiddle 来让人们更轻松。 http://jsfiddle.net/bJxe3/19/ http://jsfiddle.net/bJxe3/19/

Instead of adding a character at a time, you could update the content with a substring of the string up to the index.您可以使用字符串的子字符串更新内容,而不是一次添加一个字符,直到索引。 If the character at the index is a less-than sign (<), simply skip ahead to the next greater-than sign (>).如果索引处的字符是小于号 (<),只需向前跳到下一个大于号 (>)。

Snippet:片段:

 const printSentence = (id, sentence, speed = 50) => { let index = 0; let element = document.getElementById(id); let timer = setInterval(function() { const char = sentence[index]; if (char === '<') { index = sentence.indexOf('>', index); // skip to greater-than } element.innerHTML = sentence.slice(0, index); if (++index === sentence.length) { clearInterval(timer); } }, speed); } // printSentence printSentence( 'contentDiv', 'This is some cool <strong>content</strong>.<p>Paragraph of content</p><ul><li>This<li>is<li>a<li>test</ul><table><tr><th>Header 1<th>Header 2<tr><td>Row 2, Col 1<td>Row 2, Col 2</table>', 50 );
 body, table {font: 12px verdana;} table {border-spacing: 0;} td,th {border: 1px solid gray;} th {background: #def;}
 <div id="contentDiv"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM