/* Let's review the motion function before the time movement.
usually everyone writes a motion frame, a timer (timer), a step (step is the distance of each movement ), a position (current) a target position (target), Then determine the current position plus the relationship between the step size and the target position.
You can do it.
That's it.
var Obj=document.getelementbyid ("div");
/* To get the current position of the element, is to get the CSS, obj.style.left= "px", so it is OK, no problem,
But if you write the Var left=obj.style.left, you can't get it, CSS gets it, you need to use the method */
function Getcss (obj,attr) {
/*window.getcomputedstyle compatible Standard browser Google firefox Apple browser
Currentstyle is compatible with IE */
return Window.getcomputedstyle?getcomputedstyle (obj) [attr]:obj.currentstyle[attr];
}
/*attr is the element attribute to be changed (left or top);
Step's positive and negative decision direction of movement */
function Move (obj,target,step,attr)
{
var timer=null,current=0;
Clearinterval (timer);
Timer=setinterval (function () {
Current=parsefloat (Getcss (obj,attr));//Remove Unit px
if ((current+step-target) *step<0)//motion down or up satisfies this condition
{
obj.style[attr]=current+step+ "px";
}
else{
obj.style[attr]=target+ "px";
Clearinterval (timer);
}
},1000/60);
}
Time motion function
function Getcss (obj,attr) {
return Window.getcomputedstyle?window.getcomputedstyle (obj) [attr]:obj.currentstyle[attr];
}
function $ (ID) {return document.getElementById (ID);}
/* Time movement mainly depends on the time of a formula change/total time = change of displacement/total displacement
When the ratio is 1, the exercise is over!
Time of change = current time-initial time
Position of change = current position-initial position
Displacement per move = (time of change/total time) * Total displacement
*/
function Move (obj,attr,time,target)
{
var current=parsefloat (Getcss (obj,attr));//Get the current position
var starttime=new date ();//Get Current time
var offset=target-current;//total offset, total displacement
var changetime=0;//time of Change
Obj.timer=null;
clearinterval (Obj.timer);//Use a timer before clearing it, just a good habit to avoid producing timers multiple times
Obj.timer=setinterval (function () {
changetime= (new Date ()-starttime);//Change of time
var t=changetime/time;//time/Total time of change
if (t>=1) {
obj.style[attr]=target+ "px";
clearinterval (obj.timer);
}
else{
obj.style[attr]=current+t*offset+ "px";
}
},1000/60);
}
It's not a problem after testing.
Native JS Package Time motion function