展示一步一步优化过程。
1.移动div 代码来源于网络
<!
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
>
<
meta http
-
equiv
=
"
Content-Type
"
content
=
"
text/html; charset=utf-8
"
/>
<
title
>
移动DIV
</
title
>
<
style type
=
"
text/css
"
>
.show{
background:#7cd2f8;
width:100px;
height:100px;
text
-
align:center;
position:absolute;
z
-
index:
1
;
left:100px;
top:100px;
}
</
style
>
<
script src
=
"
http://www.uuu9.com/news/css/jquery.js
"
type
=
"
text/javascript
"
></
script
>
<
script type
=
"
text/javascript
"
><!--
$(document).ready(function()
{
$(
"
.show
"
).mousedown(function(e)
{
$(
this
).css(
"
cursor
"
,
"
move
"
);
var offset
=
$(
this
).offset();
var x
=
e.pageX
-
offset.left;
var y
=
e.pageY
-
offset.top;
$(document).bind(
"
mousemove
"
,function(ev)
{
$(
"
.show
"
).stop();
var _x
=
ev.pageX
-
x;
var _y
=
ev.pageY
-
y;
$(
"
.show
"
).animate({left:_x
+
"
px
"
,top:_y
+
"
px
"
},
10
);
});
});
$(document).mouseup(function()
{
$(
"
.show
"
).css(
"
cursor
"
,
"
default
"
);
$(
this
).unbind(
"
mousemove
"
);
})
})
//
--></script>
</
head
>
<
body
>
<
div
class
=
"
show
"
>
1
</
div
>
</
body
>
</
html
>
2.我们发现里面大部分是时间绑定处理,直接绑定事件的处理函数,很容易混乱,没有层次感,先把方法独立出来
看代码:
function mousedown(e)
{
$(
this
).css(
"
cursor
"
,
"
move
"
);
var offset
=
$(
this
).offset();
var x
=
e.pageX
-
offset.left;
var y
=
e.pageY
-
offset.top;
$(document).bind(
"
mousemove
"
,{x:x,y:y},mousemove);
//
x,y要传递鼠标状态下的坐标位置
}
function mousemove(ev)
{
$(
"
.show
"
).stop();
var _x
=
ev.pageX
-
ev.data.x;
var _y
=
ev.pageY
-
ev.data.y;
$(
"
.show
"
).animate({left:_x
+
"
px
"
,top:_y
+
"
px
"
},
10
);
}
function mouseup()
{
$(
"
.show
"
).css(
"
cursor
"
,
"
default
"
);
$(
this
).unbind(
"
mousemove
"
);
}
$(document).ready(function()
{
$(
"
.show
"
).mousedown(mousedown);
$(document).mouseup(mouseup);
})
修改后是不是逻辑比较清晰了,但我们又发现问题了,function 有3个,还是有点乱,无组织、无纪律,我们必须给它们找个领导,把他们统一管理起来,团结在党中央周围,这样社会才会发展,生成力才能提高啊。
3.首先定义个领导结构drag,但什么样的才能称之为领导呢?领导的状态:x--鼠标状态下的坐标x位置,y--鼠标状态下的坐标y位置。领导有什么功能呢?那就是mousedown,mouseup,mousemove
看代码
var drag
=
{
x:
null
,
//
获得鼠标指针离DIV元素左边界的距离
y:
null
,
//
获得鼠标指针离DIV元素上边界的距离
mousedown: function (e) {
$(
this
).css(
"
cursor
"
,
"
move
"
);
var offset
=
$(
this
).offset();
var x
=
e.pageX
-
offset.left;
var y
=
e.pageY
-
offset.top;
$(document).bind(
"
mousemove
"
,{x:x,y:y}, drag.mousemove);
},
mouseup: function (e) {
$(
"
.show
"
).css(
"
cursor
"
,
"
default
"
);
$(
this
).unbind(
"
mousemove
"
);
},
mousemove:function(ev){
$(
"
.show
"
).stop();
var _x
=
ev.pageX
-
ev.data;
var _y
=
ev.pageY
-
ev.data;
$(
"
.show
"
).css({left:_x
+
"
px
"
,top:_y
+
"
px
"
});
}
}
现在所有的功能都集中于drag,你只要找到这个领导,什么是都好办多了。呵呵。
$(document).ready(function()
{
$(".show").mousedown(mousedown);
$(document).mouseup(mouseup);
})
是不是逻辑很清晰,代码很明了。
代码一定要抓住一主线,这样才易于读懂、扩展和维护。
这主线是ready包着的mosuedown和mouseup。代码的封装很重要,必须要保证每块的有独立的功能,
他们之间的耦合性一定要降低最低。