<div style="width:140px; height:140px; background-color:pink; cursor:pointer; position:absolute;" id="divBlock" ></div> <script> f=0.003; // 运动阻尼 k=0.8; // 碰撞弹性系数 g=0.6; // 重力加速度 var obj, timeHandle; window.onload=init; function init(){ obj=document.getElementById("divBlock"); obj.speedX=0; obj.speedY=0; obj.lastX=obj.offsetLeft; obj.lastY=obj.offsetTop; obj.move=function(){ this.stop(); var x, y, mx, my; x=this.offsetLeft; y=this.offsetTop; mx=document.body.clientWidth-this.offsetWidth; // 计算允许运动的最大范围 my=document.body.clientHeight-this.offsetHeight; this.speedY+=g; // 计算重力加速度影响的y方向速度 this.speedX-=f*this.speedX*this.speedX*(this.speedX>0?1:-1); // 计算阻尼后的速度 this.speedY-=f*this.speedY*this.speedY*(this.speedY>0?1:-1); // 阻尼大小和速度平方成正比 if(Math.abs(this.speedX)>mx||Math.abs(this.speedY)>my){ this.speedX=this.speedX%mx; this.speedY=this.speedY%my; } x+=this.speedX; y+=this.speedY; // 计算坐标 if(x<0){ x=-x; this.speedX=Math.abs(this.speedX)*k; } // 计算边界碰撞 if(y<0){ y=-y; this.speedY=Math.abs(this.speedY)*k; } if(x>mx){ x=mx*2-x; this.speedX=-Math.abs(this.speedX)*k; } if(y>my){ y=my*2-y; this.speedY=-Math.abs(this.speedY)*k; } if(Math.abs(this.speedX)<1)this.speedX=0; // 消除数据下溢 if(Math.abs(my-y)<4&&Math.abs(this.speedY)<4){ y=my; this.speedY=0; } // 消除临界状态的抖动 this.style.left=parseInt(x)+"px"; // 实现移动 this.style.top=parseInt(y)+"px"; this.timeHandle=setTimeout("obj.move();",10); } obj.stop=function(){ clearTimeout(this.timeHandle); } obj.onmousedown=function(){ this.stop(); divBlock_event_mousedown(arguments[0]); } obj.move(); } function divBlock_event_mousedown(e){ var e, temp; e=window.event?window.event:e; obj.startX=e.clientX-obj.offsetLeft; obj.startY=e.clientY-obj.offsetTop; document.onmousemove=document_event_mousemove; temp=document.attachEvent?document.attachEvent("onmouseup",document_event_mouseup):document.addEventListener("mouseup",document_event_mouseup,""); } function document_event_mousemove(e){ var e; e=window.event?window.event:e; with(obj.style){ position="absolute"; left=e.clientX-obj.startX+"px"; top=e.clientY-obj.startY+"px"; } obj.speedX=(obj.offsetLeft-obj.lastX)*3; obj.speedY=(obj.offsetTop-obj.lastY)*3; obj.lastX=obj.offsetLeft; obj.lastY=obj.offsetTop; } function document_event_mouseup(e){ var temp; document.onmousemove=""; temp=document.detachEvent?document.detachEvent("onmouseup",document_event_mouseup):document.removeEventListener("mouseup",document_event_mouseup,""); obj.move(); } </script>
Tips:You can change the code before run.
Recent Comments