<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title></title> <style> * {margin:0;padding:0; }Div{Margin-top:10px;width:100px;Height:50px;Background-color:Purple;position:Absolute; } </style></Head><Body><inputtype= "button"value= "Move to 400px"ID= "BT1"/><inputtype= "button"value= "Move to 800px"ID= "BT2"/><DivID= "DV"></Div><Scriptsrc= "Common.js"></Script><Script>my$ ("BT1"). onclick= function() {Animate (my$ ("DV"), -); }; my$ ("BT2"). onclick= function() {Animate (my$ ("DV"), -); }; //Animation Functions functionanimate (element, target) {//a timer to clean up (only one timer is generated) varTimeid=SetInterval (function () { //get the current position of Div var Current=Element.offsetleft;//number Type no px //how many pixels each div moves-----steps varStep= Ten; Step= Current<Target?Step:-step; //the distance after each move Current+=step; //determines whether the position after the current move reaches the target location if(Math.Abs (Target-Current )>Math.Abs (STEP)) {Element.style.left= Current+ "px"; } Else { //Cleaning Timersclearinterval (Timeid); Element.style.left=Target+ "px"; } }, -) }</Script></Body></HTML>
Common.js:
/** * Created by Administrator on 2018/7/22.*/functionmy$ (ID) {returndocument.getElementById (ID);}//set any text content in the middle of a labelfunctionSetinnertext (element, text) {//determine if the browser supports this property if(typeofElement.textcontent = = "undefined") {Element.innertext=text; } Else{element.textcontent=text; }}//get text content in the middle of any labelfunctionGetinnertext (Element) {if(typeofElement.textcontent = = "undefined") { returnElement.innertext; } Else { returnelement.textcontent; }}//gets the first child element of any parent elementfunctionGetfirstelementchild (Element) {if(Element.firstelementchild) {//true Support returnElement.firstelementchild; } Else { varnode = Element.firstchild;//first child node while(Node && node.nodetype! = 1) {node=node.nextsibling; } returnnode; }}//gets the last child element of any parent elementfunctionGetlastelementchild (Element) {if(element.lastelementchild) {returnElement.lastelementchild; } Else { varnode =Element.lastchild; while(Node && node.nodetype! = 1) {node=node.previoussibling; } returnnode; }}//binding arbitrary events to arbitrary elements//parameter 1: any element//Parameter 2: Event Type//Parameter 3: event handler functionfunctionAddeventlistner (element, type, fn) {//determine if the browser supports this method if(Element.addeventlistener) {Element.addeventlistener (TYPE,FN,false); }Else if(element.attachevent) {element.attachevent ("On" +type, fn); }Else{element["On" +type] =fn; }}
JavaScript wrapper animation function