Article From:https://segmentfault.com/q/1010000012143149

Question: add animations to the text to let it appear in sequence (interval 100ms). What’s wrong with the following code? Or give other better solutions.

<ul class="u1"></ul>
$(function () {
    var str = 'Linear transformation preserves straight lines and parallel lines, while linear transformation preserves straight lines, other geometric properties, such as length, angle, area and volume, may be changed. In simple terms, the linear transformation may "stretch" the coordinate system, but it will not "bend" or "roll" the coordinate system. This function is mainly to bring usA "change matrix" operation of the connecting line dragged after the elastic ball is dragged.Var arr = str.split ('');For (VaR I = 0; I < arr.length;I++) {SetTimeout (function () {()Console.log (arr[i]); / / undefined?$('.u1').Append ('< span class= "anim zoomInRight" > "+ arr[i] +'< /span>");}, 100 *I);}});

The current effect is like picture (animation is OK, only text does not come out):

Desired results:

Answer 0:

var Change to let

   for (let i = 0; i < arr.length; i++) {
        setTimeout(function() {
            console.log(arr[i]); // undefined?
            $('.u1').append('<span class="anim zoomInRight">' + arr[i] + '</span>');
        }, 100 * i);


            setTimeout(function() {
            $('.u1').append('<span class="anim zoomInRight">' + arr[i] + '</span>');
        }, 100 * i);

Answer 1:

First, the string can be traversed in the for loop without turning into an array, and setTimeout is asynchronous and it keeps a reference to the I, and the loop is over when the timer is called after 100 milliseconds. When the function executes calling I, the value of I is the length of the string, arr[iThat’s undefined. It can be modified as follows:
(function(i){setTimeout(function() {

        console.log(arr[i]); // undefined?
        $('.u1').append('<span class="anim zoomInRight">' + arr[i] + '</span>');
    }, 100 * i)})(i);

Answer 2:

The problem of the scope of action,istaysettimeoutThere is no defined value in it, so it isundefined

Answer 3:
$('.u1').append('<span class="anim zoomInRight">' + arr[i] + '</span>');console.log(i);

Add a I in the back and see what I is at the time of execution.
Then go to the search, circulate the closure.

Link of this Article: JS adds animation to text in turn

Leave a Reply

Your email address will not be published. Required fields are marked *