animation with node appendChild() html

2019-07-14 02:02发布

问题:

I'm very very new to web development, and I'm trying to create a webpage that will extend down the page as a button is clicked. I found this link, which contains this code:

HTML:

<ul id="myList"><li>Coffee</li><li>Tea</li></ul>

<p id="demo">Click the button to append an item to the list</p>

<button onclick="myFunction()">Try it</button>

JavaScript:

function myFunction()
{
    var node=document.createElement("LI");
    var textnode=document.createTextNode("Water");
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
}

Which will add information. I want to do this so it animates in, not just appears. How would I go about this?

Any help or tutorials are appreciated. Thank you!

回答1:

You would have to read up a bit on jQuery, but there's a description of pretty much what you want here: jQuery using append with effects

The principle is to create a jQuery object first, that represents the element you want to append, making sure that it has a style setting that ensures that it is not immediately visible (e.g. display: none).

You then append the element into the page (at which point the browser won't render it due to the style setting), and finally use a jQuery method to have it animate into view.



回答2:

I recommend you use bootstrap collapse.



回答3:

The most usual way is to control the CSS style through javascript, as such (these are just examples):

// controlling the opacity of an element
document.getElementById(yourElementId).style.opacity = 0.5;
// controlling the position(top) of an element
document.getElementById(yourElementId).style.top = 10;

You want to create a set of javascript for whatever animation you want to do, and put that code into the function which is called on the click. Example of a fade-in effect may be :

function myFunction()
{
var node=document.createElement("LI");
var textnode=document.createTextNode("Water");

// fade-in effect. The opacity starts from zero, and increases through 10steps.
node.style.opacity = 0;
for (var i=1;i<=10;i++) {
    node.style.opacity = i/10;
}
node.style.opacity = 1;
// end of fade-in effect

node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}

(Haven't thoroughly tested it so it may be shaky)

My example was a fade-in, but just do the same for any type of position change or color change or whatever.