Javascript typing effect

前端 未结 6 1347
刺人心
刺人心 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条回答
  •  天涯浪人
    2021-01-01 00:06

    Okay, I don't like any of the above code. Your original code also doesn't stop running once it reaches the end of the input text, and I don't believe any of the other suggested solutions stop either.

    Here's a rewritten function in pure JS:

    function type(i, t, ie, oe) {
        input = document.getElementById(ie).innerHTML;
        document.getElementById(oe).innerHTML += input.charAt(i);
        setTimeout(function(){
            ((i < input.length - 1) ? type(i+1, t, ie, oe) : false);
        }, t);
    }
    

    Which you can call like so:

    type(0, 100, "text", "screen");
    

    The parameters are: beginning index, speed, input element, output element

    Your HTML will look something like this:

    You can rename the divs to whatever you like, as long as you update the parameters accordingly. I'm sure there's an easier way to write this as well, but I like this method the most.


    Demo

    function type(i, t, ie, oe) {
        input = document.getElementById(ie).innerHTML;
        document.getElementById(oe).innerHTML += input.charAt(i);
        setTimeout(function(){
            ((i < input.length - 1) ? type(i+1, t, ie, oe) : false);
        }, t);
    }
    
    type(0, 100, "text", "screen");

提交回复
热议问题