<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> body{margin:0;padding:0;} div{width:100px;height:100px;background:red;position:absolute;left:0;top:30px;} </style> <script> var ispeedX = 0; var ispeedY = 0; window.onload = function(){ var oBtn = document.getElementsByTagName('input')[0]; var oDiv = document.getElementsByTagName('div')[0]; oBtn.onclick = function(){ elasticStartMove(oDiv); }; var lastX = 0; /*拖的快就快碰撞,拖的慢就慢碰撞*/ var lastY = 0; oDiv.onmousedown = function(ev){ var ev = ev || event; var disX = ev.clientX-this.offsetLeft; var disY = ev.clientY-this.offsetTop; document.onmouseover = function(ev){ var oEvent = ev || event; var l = oEvent.clientX-disX; var t = oEvent.clientY-disY; ispeedX = l-lastX; ispeedY = t-lastY; lastX = l; lastY = t; oDiv.style.left = l+'px'; oDiv.style.top = t+'px'; }; document.onmouseup = function(){ document.onmouseover = document.onmouseup = null; elasticStartMove(oDiv); }; }; }; function elasticStartMove(obj){ clearInterval(obj.timer); obj.timer = setInterval(function(){ ispeedY += 3; /*受重力因素,越来越快,加上重力摩擦会变得越来越小*/ var t = obj.offsetTop+ispeedY; var l= obj.offsetLeft+ispeedX; // alert("obj.offsetTop:"+obj.offsetTop+"ispeedY:"+ispeedY+"t:"+t); if(t >= document.documentElement.clientHeight - obj.offsetHeight){ ispeedY *= -0.8;/*重力因素,让速度越来越小,高度不会变*/ ispeedX *= 0.8; t = document.documentElement.clientHeight - obj.offsetHeight; }else if(t<=0){ ispeedY *= -0.8; t = 0; } if(l >= document.documentElement.clientWidth - obj.offsetWidth){ ispeedX *= -0.8; l = document.documentElement.clientWidth - obj.offsetWidth; //避免超出范围碰撞,出现滚动条 }else if(l<=0){ ispeedX *= -0.8; l = 0 } /*如果isped为小数,会往回跑,300.3-300 299.5->299*/ if(Math.abs(ispeedX) <1){ ispeedX = 0; } if(Math.abs(ispeedY) <1){ ispeedY = 0; } if(ispeedX ==0 && ispeedY == 0 && t == document.documentElement.clientHeight - obj.offsetHeight ){ clearInterval(obj.timer); }else{ obj.style.top = t+'px'; obj.style.left = l+'px'; } },30); } </script> </head> <body> <input type='button' value='开始运动'/> <div></div> </body> </html>