预览图
效果图帧数有点低...., 下面附上代码, 大家仔细研究, 总之它会在当前可视区内弹来弹去
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ceshi</title>
<style>
*{
margin: 0;
top: 0;
}
#demo{
border-radius: 50%;
background: pink;
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="demo">
</div>
<script type="text/javascript">
var Odiv = document.getElementById('demo');
Odiv.onmousedown = function (e) {//拖拽小物体
clearInterval(this.timer);
var event = e || window.event;
var disX = event.clientX - this.offsetLeft;
var disY = event.clientY- this.offsetTop;
var _self = this;
var ispeedX = 0;
var ispeedY = 0;
var lastX = Odiv.offsetLeft;
var lastY = Odiv.offsetTop;
document.onmousemove = function (e) {//实时更新当前小物体的位置
event = e || window.event;
var newL = event.clientX - disX;
var newT = event.clientY - disY;
ispeedX = newL - lastX;
ispeedY = newT - lastY;
lastX = newL;
lastY = newT;
_self.style.left = newL + 'px';
_self.style.top = newT + 'px';
}
document.onmouseup = function() {//当鼠标移开时, 触发事件
document.onmousemove = null;//移除onmousemove事件
document.onmouseup = null;
startTSMove(_self, ispeedX, ispeedY);
}
}
function startTSMove (obj, ispeedX, ispeedY) {
clearInterval(obj.timer);
var g = 3;//模拟重力加速度
obj.timer = setInterval(function() {
ispeedY += g;
var newL = obj.offsetLeft + ispeedX;
var newT = obj.offsetTop + ispeedY;
if(newT >= (document.documentElement.clientHeight - obj.offsetHeight)){
ispeedY *= -1;//每次撞到当前可视区窗口时, 速度变为相反
ispeedX *= 0.8;//每次撞击模拟动能损失
ispeedY *= 0.8;
newT = document.documentElement.clientHeight - obj.offsetHeight;
}
if(newT < 0){
ispeedY *= -1;
ispeedY *= 0.8;
newT = 0;
}
if(newL >= (document.documentElement.clientWidth - obj.offsetWidth)){
ispeedX *= -1;
ispeedX *= 0.8;
newL = document.documentElement.clientWidth - obj.offsetWidth;
}
if(newL < 0){
ispeedX *= -1;
ispeedX *= 0.8;
newL = 0;
}
if(Math.abs(ispeedX) < 1){
ispeedX = 0
}
if(Math.abs(ispeedY) < 1){
ispeedY = 0
}
if(ispeedX === 0 && ispeedY === 0 && newT === (document.documentElement.clientHeight - obj.offsetHeight) ){//当停下来时, 清除定时器
console.log('over');
clearInterval(obj.timer);
}
obj.style.left = newL + 'px';//实时更新当前小物体的位置
obj.style.top = newT + 'px';
}, 30)
}
</script>
</body>
</html>