Javascript typing effect

前端 未结 6 1383
刺人心
刺人心 2020-12-31 23:28

The issue arises from the same issue as last time. My websites run off a static domain, so I want to be able to use this script on each site without making duplicate copies.

6条回答
  •  灰色年华
    2020-12-31 23:43

    Here is an approach using promises for sleeping between key presses.

    Here is a link for the repo at Github, but the code is basically this:

    class Typer {
    
        constructor(typingSpeed, content, output) {
    
            this.typingSpeed = typingSpeed;
            // Parses a NodeList to a series of chained promises
            this.parseHtml(Array.from(content), output);
        };
    
        makePromise(node, output) {
    
            if (node.nodeType == 1) // element 
            {
                // When a new html tag is detected, append it to the document
                return new Promise((resolve) => {
                    var tag = $(node.outerHTML.replace(node.innerHTML, ""));
                    tag.appendTo(output);
                    resolve(tag);
                });
    
            } else if (node.nodeType == 3) // text
            {
                // When text is detected, create a promise that appends a character
                // and sleeps for a while before adding the next one, and so on...
                return this.type(node, output, 0);
            } else {
                console.warn("Unknown node type");
            }
        }
    
        parseHtml(nodes, output) {
            return nodes.reduce((previous, current) => previous
                .then(() => this.makePromise(current, output)
                    .then((output) => this.parseHtml(Array.from(current.childNodes), output))), Promise.resolve());
        }
    
        type(node, output, textPosition) {
            var textIncrement = textPosition + 1;
    
            var substring = node.data.substring(textPosition, textIncrement);
    
            if (substring !== "") {
                return new Promise(resolve => setTimeout(resolve, this.typingSpeed))
                    .then(() => output.append(substring))
                    .then(() => this.type(node, output, textIncrement));
            }
    
            return Promise.resolve(output);
        }
    }
    

提交回复
热议问题