<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body{
width:100%;
height:100%;
}
position: absolute;
width:100px;
height:100px;
border-radius: 50%;
background: red;
top:100px;
cursor: move;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box = document.getElementById("box");
var maxL = document.documentElement.clientWidth - box.offsetWidth;
var maxT = document.documentElement.clientHeight-box.offsetHeight;
box.onmousedown = function (e) {
// 记录鼠标当前的位置;放到box自定义属性上
this["strX"] = e.clientX;
this["strY"] = e.clientY;
// 记录盒子的位置
this["strL"] = parseFloat(getComputedStyle(box).left);
this["strT"] = parseFloat(getComputedStyle(box).top);
//绑定move和up;
var that = this;
document.body.onmousemove = function (e) {
move.call(that,e)
}
document.body.onmouseup = function(e){
up.call(that,e)
}
}
function move(e) {
var curL = e.clientX - this["strX"];
var curT = e.clientY - this["strY"];
var l = this["strL"]+curL;
var t = this["strT"]+curT;
if(l>=maxL){
l = maxL;
}
if(l<=0){
l=0;
}
if(t>=maxT){
t=maxT;
}
if(t<=0){
t=0;
}
this.style.left = l+"px";
this.style.top = t+ "px";
getSpeed.call(this)
console.log(100);
}
function up() {
document.body.onmousemove = null;
document.body.onmouseup = null;
drop.call(this);
fly.call(this);
}
// 自由落体运动;
var maxY = document.documentElement.clientHeight - box.offsetHeight;
function drop() {
if(!this.dropSpeed){
// 如果是第一次执行drop方法;会执行此处的代码
this.dropSpeed = 1;
}else{
// 以后每一次都执行这里的代码;
this.dropSpeed+=3;
}
this.dropSpeed*=0.97;
var curT = this.offsetTop + this.dropSpeed;
if(curT>=maxY){
this.dropSpeed*=-1;
this.style.top = maxY + "px";
this.flag++;
}else{
this.style.top = curT + "px";
this.flag = 1;
}
if(this.flag>2){
clearTimeout(this.dropTimer);
}else{
this.dropTimer = setTimeout(drop.bind(this),18);
}
}
function fly() {
this.flySpeed*=0.99;
var curPosi = this.offsetLeft + this.flySpeed;
if(curPosi>=maxL){
this.style.left = maxL + "px";
this.flySpeed*=-1;
}else if(curPosi<=0){
this.style.left = 0+ "px";
this.flySpeed*=-1;
}else{
this.style.left = curPosi + "px";
}
if(Math.abs(this.flySpeed)<0.5){
clearTimeout(this.flyTimer)
}else{
this.flyTimer = setTimeout(fly.bind(this),18)
}
}
function getSpeed() {
// this---> box;
if(!this.prevPosi){
this.prevPosi = this.offsetLeft;
}else{
this.flySpeed = this.offsetLeft - this.prevPosi;
this.prevPosi = this.offsetLeft;
}
}
</script>
</body>
</html>