<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
position: absolute;
left: 0px;
top:0px;
width: 100px;
height: 100px;
background:orangered;
}
span{
position:absolute;
left:0px;
top: 0px;
width:5px;
height:5px;
background:black;
}
</style>
</head>
<body>
<div></div>
<span></span>
<script>
var div = document.getElementsByTagName('div')[0];
var lastX = div.offsetLeft;
var lastY = div.offsetTop;
div.onmousedown = function(e){
clearInterval(div.timer);//用于空中抓取
var event = e || window.event;
var disX = event.clientX - this.offsetLeft;//鼠标点击的位置与左边的差值
var disY = event.clientY - this.offsetTop;
var that = this;
var isSpeedX = 0;
var isSpeedY = 0;
document.onmousemove = function(e){
var newLeft = e.clientX - disX;//左边距=鼠标点击的位置-上面的差值
var newTop = e.clientY - disY;
isSpeedX = newLeft - lastX;
isSpeedY = newTop - lastY;
lastX = newLeft;
lastY = newTop;
that.style.left = newLeft + 'px';
that.style.top = newTop + 'px';
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
startMove(that,isSpeedX,isSpeedY);
}
}
function startMove(obj,isSpeedX, isSpeedY){
clearInterval(obj.timer);
var g = 6;
obj.timer = setInterval(function(){
isSpeedY += g;
var newLeft = obj.offsetLeft + isSpeedX;
var newTop = obj.offsetTop + isSpeedY;
if(newTop >= document.documentElement.clientHeight - obj.offsetHeight){
isSpeedY *=-1;
isSpeedY *= 0.8;
isSpeedX *= 0.8;
newTop = document.documentElement.clientHeight - obj.offsetHeight;
}
if(newLeft >= document.documentElement.clientWidth - obj.offsetWidth){
isSpeedX *= -1;
isSpeedX *= 0.8;
isSpeedY *= 0.8;
newLeft = document.documentElement.clientWidth - obj.offsetWidth;
}
if(newTop <= 0){
isSpeedY *=-1;
isSpeedX *= 0.8;
isSpeedY *= 0.8;
newTop = 0;
}
if(newLeft <= 0){
isSpeedX *= -1;
isSpeedX *= 0.8;
isSpeedY *= 0.8;
newLeft = 0;
}
//停止位置判断,当在空中,Vx=0&&Vy=0时不是停止状态
if(Math.abs(isSpeedX) < 1){
isSpeedX = 0;
}
if(Math.abs(isSpeedY) < 1){
isSpeedY = 0;
}
if(isSpeedX == 0&& isSpeedY ==0 && newTop == document.documentElement.clientHeight - obj.clientHeight){
clearInterval(obj.timer);
}
obj.style.left = newLeft + 'px';
obj.style.top = newTop + 'px';
},30)
}
</script>
</body>
</html>