Encapsulate slow motion (variable speed) animation - add any attribute
1. The original variable speed animation function is to obtain specific attributes (in the previous case, it was moved to the right, so it acquired the left attribute)
2. Now it is changed to obtain any attribute and move it to the specified target, which is equivalent to adding an attribute to the original animate(element,target) function and changing it to the animate(element, attr, target) function
3. Change 1: in the position of getting the current element, var current, use getStyle to get it, because what you get is a string type, change a parseInt to a number type;
4. Change 2: when moving the steps, the current position of the element is equal to current+"px", the element.style.left is updated to element.style[attr], and the specific element is replaced by any element
The effect obtained is that any style attribute of any element can be moved to the specified target location
The attr position can be changed to left, heigth, top, bgc, etc
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <style> * { margin: 0; padding: 0; } div { margin-top: 20px; width: 200px; height: 100px; background-color: green; position: absolute; left: 0; top: 0; } </style> </head> <body> <input type="button" value="Move to 400 px" id="btn1" /> <input type="button" value="Move to 800 px" id="btn2" /> <div id="dv"> <script src="common.js"></script> <script> //Click the button to move div my$("btn1").onclick = function () { //obtain div here left Current location of,Achieve goal 400 // animate(my$("dv"),"left",400); //obtain div Width at this time,Achieve goal 200 animate(my$("dv"), "width", 200); }; //Get the current property value of any property: Use previously encapsulated getStyle function function getStyle(element, attr) { //Determine whether the browser supports this method return window.getComputedStyle ? window.getComputedStyle(element, null)[attr] : element.currentStyle[attr]; } //Uniform animation //element---element //attr---Property name //target---Target location function animate(element, attr, target) { //Cleaning timer clearInterval(element.timeId); element.timeId = setInterval(function () { //Get the current location of the element var current = parseInt(getStyle(element, attr));//Number type//=============================== //Steps moved var step = (target - current) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); current += step; element.style[attr] = current + "px";//============================================ if (current == target) { //Cleaning timer clearInterval(element.timeId); } //Test code: console.log("Target location:" + target + ",current location:" + current + ",Steps per move:" + step); }, 20); } </script> </div> </body> </html>