拖拽

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box{position: relative;width: 200px;height: 200px;background: red; cursor: pointer;}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script type="text/javascript">
// window.onload = function (){
// // 获取元素和初始值
// var oBox = document.getElementById('box'),
// disX = 0, disY = 0;
// // 容器鼠标按下事件
// oBox.onmousedown = function (e){
// var e = e || window.event;
// disX = e.clientX - this.offsetLeft;
// disY = e.clientY - this.offsetTop;
// document.onmousemove = function (e){
// var e = e || window.event;
// oBox.style.left = (e.clientX - disX) + 'px';
// oBox.style.top = (e.clientY - disY) + 'px';
// };
// document.onmouseup = function (){
// document.onmousemove = null;
// document.onmouseup = null;
// };
// return false;
// };
//};


// window.onload = function (){
// var drag = new Drag('box');
// drag.init();
// };
//
// function Drag(id){
// this.obj = document.getElementsByClassName(id)[0];
// this.disX=0;
// this.disY=0;
// }
//
// Drag.prototype.init=function(){
// var _this = this;
// _this.obj.onmousedown=function(e){
// var e = e||window.event;
// _this.mouseDown(e);
// return false;
// }
// }
// Drag.prototype.mouseDown = function(e){
// var _this = this;
// _this.disX = e.clientX - _this.obj.offsetLeft;
// _this.disY = e.clientY - _this.obj.offsetTop;
// document.onmousemove=function(e){
// var e = e||e.window.event;
// _this.mouseMove(e);
// }
// document.onmouseup=function(){
// document.onmousemove=null;
// document.onmouseup=null;
// }
// }
// Drag.prototype.mouseMove=function(e){
// this.obj.style.left = (e.clientX - this.disX) + 'px';
// this.obj.style.top = (e.clientY - this.disY) + 'px';
// }
// Drag.prototype.mouseUp = function (){
// document.onmousemove = null;
// document.onmouseup = null;
// };

window.onload=function(){
var drag = {
box:document.getElementsByClassName("box")[0],
disX:0,
disY:0,
init:function(){
var _this = this;
_this.box.onmousedown=function(){
_this.mouseDown();
}
return false;
},
mouseDown:function(e){
var e = e||window.event;
var _this = this;
_this.disX = e.pageX - _this.box.offsetLeft;
_this.disY = e.pageY - _this.box.offsetTop;
document.onmousemove = function(e){
var e = e||window.event;
_this.box.style.left = (e.pageX - _this.disX)+"px";
_this.box.style.top = (e.pageY - _this.disY)+"px"
}
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
}

}


drag.init();


}


</script>
</html>

posted @ 2017-02-07 16:10  duguangyan  阅读(142)  评论(0编辑  收藏  举报