Encapsulation functions
function Animate (obj,endposition) { clearinterval (obj.timer); = SetInterval (function() { var step = (endposition-obj.offsetleft)/10; Step = step > 0? Math.ceil (STEP): Math.floor (step); = obj.offsetleft + step + ' px '; if (Obj.offsetleft = = endposition) {clearinterval (Obj.timer)} },() }
Case
<!Doctyle HTML><HTML><Head> <MetaCharSet= "Uft-8" /> <style>#box{width:100px;Height:100px;background:#dfd;position:Absolute; Left:100px;Top:100px;} </style></Head><Body><ButtonID= "BTN1">200</Button><ButtonID= "BTN2">600</Button><DivID= "box"></Div></Body></HTML><Script> varBTN1=document.getElementById ('BTN1'); varbtn2=document.getElementById ('btn2'); varBox=document.getElementById ('Box'); Btn1.onclick= function() {Animate (box, $)} Btn2.onclick= function() {Animate (box, -) } functionAnimate (Obj,endposition) {clearinterval (Obj.timer); Obj.timer=SetInterval (function(){ varStep=(Endposition-obj.offsetleft)/Ten;Step=Step> 0 ?Math.ceil (STEP): Math.floor (step); Obj.style.left=Obj.offsetleft+Step+ 'px'; if(Obj.offsetleft==endposition) {clearinterval (Obj.timer)}// //Use = = Do not use >=, otherwise, in this case, if you have scrolled to 600 position, click 200 again, you will not be able to return to the 200 position }, -) } </Script>
Slow Motion Package