现在的位置: 首页 > 综合 > 正文

一步一步理解拖拽Drag(一)

2012年08月01日 ⁄ 综合 ⁄ 共 1692字 ⁄ 字号 评论关闭

拖拽三部曲原理:
     1、鼠标按下;
     2、鼠标移动;
     3、鼠标抬起。

View Code

<!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>
<title>Drag一步一步理解拖拽</title>
<script type="text/javascript">
var base = {
getId:
function (id) {
return document.getElementById(id);
},
addEvent:
function (elem, type, fn) {
if (elem.addEventListener) {
elem.addEventListener(type, fn,
false);
}
else if (elem.attachEvent) {
elem.attachEvent(
"on" + type, fn);
}
else {
elem[
"on" + type] = fn;
}
},
removeEvent:
function (elem, type, fn) {
if (elem.removeEventListener) {
elem.removeEventListener(type, fn,
false);
}
else if (elem.detachEvent) {
elem.detachEvent(
"on" + type, fn);
}
else {
elem[
"on" + type] = null;
}
}
};

function Drag(obj) {
this.obj = obj;
var _this = this;
base.addEvent(obj,
"mousedown", function (event) {
_this.startDrap(event);
});
}

Drag.prototype
= {
startDrap:
function (event) {
var _this = this;

this.mousemoveHandle = function (event) {
_this.move();
};

this.mouseupHandle = function () {
_this.stopDrag();
};

base.addEvent(document,
"mousemove", this.mousemoveHandle);

base.addEvent(document,
"mouseup", this.mouseupHandle);

base.getId(
"mdiv").innerHTML = "鼠标被按下了";
},
move:
function () {
base.getId(
"mdiv").innerHTML = "鼠标移动中。。。。";

this.obj.style.left = event.clientX - this.obj.offsetLeft + "px";
this.obj.style.top = event.clientY - this.obj.offsetTop + "px";
},
stopDrag:
function () {
base.removeEvent(document,
"mousemove", this.mousemoveHandle);
base.removeEvent(document,
"mouseup", this.mouseupHandle);

base.getId(
"mdiv").innerHTML = "鼠标抬起了";
}
};


base.addEvent(window,
"load", function () {
var tmp = base.getId("mdiv");
var b = new Drag(tmp);
});
</script>
</head>
<body>
<div id="mdiv" style="width: 300px; height: 100px; border: 1px solid red; position: absolute">
</div>
</body>
</html>

 

抱歉!评论已关闭.