<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box{
position: absolute;
width: 100px;
height: 100px;
background: #000;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script type="text/javascript">
var obj = {
data: { //設置公共變量
oTop:0,
oLeft:0,
flag:false
},
controller: { //控制器裏的鼠標事件
init: function(){ //初始化函數
var box = document.getElementById("box");
this.mousedown(box);
this.mousemove(box);
this.mouseup();
},
mousedown:function(ele){
ele.onmousedown = function(e){
e = event || window.event;
obj.data.oTop = e.screenY - ele.offsetTop;
obj.data.oLeft = e.screenX - ele.offsetLeft;
obj.data.flag = true;
}
},
mousemove: function(ele){
document.onmousemove = function(e){
e = event || window.event;
if (obj.data.flag) {
var mH = parseInt(e.screenY - obj.data.oTop);
var ml = parseInt(e.screenX - obj.data.oLeft);
obj.view.show(ele,mH,ml);
}
}
},
mouseup: function(){
document.onmouseup = function(){
obj.data.flag = false;
}
}
},
model: { // 模型裏沒有數據的操做所以不用寫
},
view: { //視圖的展現
show: function(ele,y,x){
ele.style.top = y +'px';
ele.style.left = x +'px';
}
}
}
obj.controller.init();
</script>
</html>javascript