简体   繁体   中英

Javascript basic animation rotate sting

I'm having a hard time understanding whats going in in this function. Can someone break it down step by step?

<html> 
    <head>
        <title>JavaScript basic animation</title>
    </head> 
    <body onload="animate_string('target')">
        <p id="target">w3resource</p>
    </body> 
</html>

function animate_string(id) {
var element = document.getElementById(id);
var textNode = element.childNodes[0]; // assuming no other children
var text = textNode.data;

  setInterval( function() {
    text = text[text.length - 1] + text.substring(0, text.length - 1);
    textNode.data = text; 
  }, 100 );
}

Sure, I can help.

First the code needs to get the text you want to animate, so it looks for the element's tag by the id attribute, in this case 'target'. So the variable element will be a 'p' tag

var element = document.getElementById(id);

The following line will actually access the hidden DOM node, called a text node, inside the element. To access the actual text string, you need to use the .data attribute of the text node element because the text node itself has a bunch of attributes associated with it and we only care about the content (data).

var textNode = element.childNodes[0]; // assuming no other children
var text = textNode.data;

Now we have a variable, text, that holds the string value of 'w3resource'. The next step is to do the animation, which is run by an interval running a function every 100ms

setInterval( function() {
   ...
}, 100 );

Inside the function that is called every 100ms, the following code is seen:

    text = text[text.length - 1] + text.substring(0, text.length - 1);
    textNode.data = text; 

First a new string of text is created by taking the last character from the string and appending the rest of the string. For example 'StackOverflow' would become 'wStackOverflo'. On the next iteration, it would convert 'wStackOverflo' to 'owStackOverfl', etc. every 100ms.

The last line of code assigns the new string to the HTML DOM element, our text node containing the text.

It would read as: " Every 10th of a second, modify the variable named text so that it contains the last character that it currently has, followed by the rest of the characters starting from the beginning "

So if you have ABCD on the first iteration it would be D (last character) followed by ABC (the rest, starting from the beginning)

The variable text comes from the content of textNode which is p with the target ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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