Home>

js drag, collision and gravity implementation code:

window.onload=function ()
{
 var odiv=document.getelementbyid ("div1");
 var lastx=0;
 var lasty=0;
 odiv.onmousedown=function (ev)
 {
 var oevent=ev || event;
 var disx=oevent.clientx-odiv.offsetleft;
 var disy=oevent.clienty-odiv.offsettop;
 document.onmousemove=function (ev)
 {
  var oevent=ev || event;
  var l=oevent.clientx-disx;
  var t=oevent.clienty-disy;
  odiv.style.left=l + "px";
  odiv.style.top=t + "px";
  ispeedx=l-lastx;
  ispeedy=t-lasty;
  lastx=l;
  lasty=t;
  document.title="x:" + ispeedx + ", y:" + ispeedy;
 };
 document.onmouseup=function ()
 {
  document.onmousemove=null;
  document.onmouseup=null;
  startmove ();
 };
 clearinterval (timer);
 };
};
var timer=null;
var ispeedx=0;
var ispeedy=0;
function startmove ()
{
 clearinterval (timer);
 timer=setinterval (function () {
 var odiv=document.getelementbyid ("div1");
 ispeedy +=3;
 var l=odiv.offsetleft + ispeedx;
 var t=odiv.offsettop + ispeedy;
 if (t>= document.documentelement.clientheight-odiv.offsetheight)
 {
  ispeedy * =-0.8;
  ispeedx *=0.8;
  t=document.documentelement.clientheight-odiv.offsetheight;
 }
 else if (t<= 0)
 {
  ispeedy * =-1;
  ispeedx *=0.8;
  t=0;
 }
 if (l>= document.documentelement.clientwidth-odiv.offsetwidth)
 {
  ispeedx * =-0.8;
  l=document.documentelement.clientwidth-odiv.offsetwidth;
 }
 else if (l<= 0)
 {
  ispeedx * =-0.8;
  l=0;
 }
 if (math.abs (ispeedx)<1)
 {
  ispeedx=0;
 }
 if (math.abs (ispeedy)<1)
 {
  ispeedy=0;
 }
 if (ispeedx == 0&&ispeedy == 0&&t == document.documentelement.clientheight-odiv.offsetheight)
 {
  clearinterval (timer);
  alert ("Stop");
 }
 else
 {
  odiv.style.left=l + "px";
  odiv.style.top=t + "px";
 }
 document.title=ispeedx;
 }, 30);
}

js elastic movement implementation code:

var left=0;//Use the left variable to store the value assigned to obj.style.left, in case the system omits decimals every time,Subtle differences in final results
var ispeed=0;
function startmove (obj, itarget)
{
 clearinterval (obj.timer);
 obj.timer=setinterval (function () {
  ispeed +=(itarget-obj.offsetleft)/5;//speed
  ispeed *=0.7;//Consider resistance
  left +=ispeed;
  if (math.abs (ispeed)<1&&math.abs (itarget-obj.offsetleft)<1) //stop condition absolute speed and distance are less than 1
  {
   clearinterval (obj.timer);
   obj.style.left=itarget + "px";//After clearing, assign the target value to obj.style.left by the way
  }
  else
  {
   obj.style.left=left + "px";
  }
 }, 30);
}
  • Previous jQuery mouseover link popup follow image example code
  • Next Python logging log rotation file does not delete the solution