拖拽案例
代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>基本的拖拽效果</title>
<style>
body {
-webkit-user-select: none;
-moz-user-select: none;
}
#div1 {
width: 100px;
height: 100px;
background: orange;
position: absolute;
top: 0;
left: 0;
cursor: move;
border-radius: 50px;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
<script>
var oDiv = document.getElementById("div1");
oDiv.onmousedown = down;
function down(e) {
this.x = this.offsetLeft;
this.y = this.offsetTop;
this.mouseX = e.clientX;
this.mouseY = e.clientY;
if (this.setCapture) {
//捕捉鼠标焦点;(IE解决方法)
this.setCapture();
//将鼠标移动和松开绑定到move和up
this.onmousemove = move;
this.onmouseup = up;
} else {
var _this = this;
var _move = bindThis(_this, move)
var _up = bindThis(_this, up);
document.onmousemove = _move;
document.onmouseup = _up;
}
}
//绑定this
function bindThis(obj, fn) {
return function(e) {
fn.call(obj, e);
};
}
function move(e) {
this.style.top = this.y + (e.clientY - this.mouseY) + "px";
this.style.left = this.x + (e.clientX - this.mouseX) + "px";
//动画代码
if (!this.prevX) {
//记录第一次/上一次事件触发的时候鼠标的x轴位置
this.prevX = e.clientX;
} else {
this.speed = e.clientX - this.prevX;
this.prevX = this.clientX;
}
}
function up(e) {
if (this.releaseCapture) {
this.releaseCapture();
this.onmousemove = null;
this.onmouseup = null;
} else {
document.onmousemove = null;
document.onmouseup = null;
}
fly.call(this);
drop.call(this);
};
//左右反弹
function fly() {
clearTimeout(this.flyTimer);
var maxRight = (document.documentElement.clientWidth || document.body.clientWidth) - this.offsetWidth;
//谁执行这个动画;this就是谁;
this.speed *= 0.93;
//边界判断
if (this.offsetLeft + this.speed >= maxRight) {
this.style.left = maxRight + "px";
this.speed *= -1;
} else if (this.offsetLeft + this.speed <= 0) {
this.style.left = 0;
this.speed *= -1;
} else {
this.style.left = this.offsetLeft + this.speed + "px";
}
/*定时器的this是window;*/
this.flyTimer = window.setTimeout(bindThis(this, fly), 30) //arguments.callee就是函数本身的意思,也可以写fly;
}
//自由落体
var g = 9.8;
var flag = 0;
function drop() {
clearTimeout(this.dropTimer);
var maxBottom = (document.documentElement.clientHeight || document.body.clientHeight) - this.offsetHeight;
if (!this.dropSpeed) {
this.dropSpeed = g;
} else {
this.dropSpeed += g;
}
//摩擦系数
this.dropSpeed *= 0.93;
//边界判断
if (this.offsetTop + this.dropSpeed >= maxBottom) {
this.style.top = maxBottom + "px";
this.dropSpeed *= -1;
flag++;
} else {
this.style.top = this.offsetTop + this.dropSpeed + "px";
flag = 0;
}
if (flag < 2) {
window.setTimeout(bindThis(this, drop), 30);
}
}
</script>