Case: mobile elements, packaged animation function
1. div want to move, to stay away from the document flow --- position: absolute
2. If the style code is provided style Tags outside is not acquired
3. If the style code is set in the style attribute and the outside can be acquired
4. Get the current position of div
console.log(my$("dv").offsetLeft);
Animate animation function package
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <style> * { margin: 0; padding: 0; } input { margin-top: 20px; } div { margin-top: 30px; width: 200px; height: 100px; background-color: pink; position: absolute; } </style> </head> <body> <input type="button" value="移动到400px" id="btn1" /> <input type="button" value="移动到800px" id="btn2" /> <div id="dv"> </ Div > < Script the src = "common.js" > </ Script > < Script > // click of a button, to move 400px My $ ( " btn1 " ) .onclick = function () { Animate (My $ ( " DV " ), 400 ); }; // click the second button, move to 800px My $ ( " btn2 " ) .onclick = function () { Animate (My $ ( " DV " ),800); }; // animation function package animate function animate (Element, target) { // first timer cleaning the clearInterval (element.timeId); // a timer will be cleaned (only generates a timer) element.timeId = the setInterval ( function ( ) { // Get current position div var current = element.offsetLeft; // digital type, no PX // div number of pixels moved per step number --- var sTEP = 10 ; sTEP = current < target ? sTEP: - sTEP; // every distance after moving Current + = STEP; // Analyzing current moving position, reaches the target position IF (the Math.abs (target - Current) > the Math.abs (STEP)) { element.style.left = Current + " PX " ; } the else { // cleanup timer the clearInterval (element.timeId); element.style.left = target + " PX " ; } }, 20 is ); } </ Script > </body> </html>