二、JavaScript实现原理简述
在AS3中,使用startDrag()就能实现拖拽,但是js中,却没有此方法,但是也是可以实现的,说穿了,挺简单的。实现拖拽方法不少,我呢,js功力尚浅,只知道一种实现原理。如下:
①鼠标按下+鼠标移动 → 拖拽
②鼠标松开 → 无拖拽
③鼠标偏移 → 拖拽距离
用JavaScript事件方法表示就是:
① onmousedown + onmousemove → startDrag()
② onmouseup → stopDrag()
③ ……
代码为:
<
html
xmlns=
"http://www.w3.org/1999/xhtml"
>
<
head
>
<
meta
http-equiv=
"Content-Type"
content=
"text/html; charset=utf-8"
/>
<
title
>demo
title
>
<
style
type=
"text/css"
>
#box{
position:
absolute;
left:
100px;
top:
100px;
padding:
5px;
background:
#f0f3f9;
font-size:
12px;
-moz-box-shadow:
2px
2px
4px
#666666;
-webkit-box-shadow:
2px
2px
4px
#666666;}
#main{
border:
1px
solid
#a0b3d6;
background:
white;}
#bar{
line-height:
24px;
background:
#beceeb;
border-bottom:
1px
solid
#a0b3d6;
padding-left:
5px;
cursor:
move;}
#content{
width:
420px;
height:
250px;
padding:
10px
5px;}
<
/
style
>
head
>
<
body
>
<
div
id=
"box"
>
<
div
id=
"main"
>
<
div
id=
"bar"
>拖拽
div
>
<
div
id=
"content"
>
内容……
div
>
div
>
div
>
<
script
type=
"text/javascript"
>
// by zhangxinxu welcome to visit my personal website http://www.zhangxinxu.com/
// zxx.drag v1.0 2010-03-23 鍏冪礌鐨勬嫋鎷藉疄鐜�
var
params = {
left:
0,
top:
0,
currentX:
0,
currentY:
0,
flag:
false
};
//拿到本元素第几个class。
var
getCss =
function(
o,
key){
return
o.
currentStyle?
o.
currentStyle[
key] :
document.
defaultView.
getComputedStyle(
o,
false)[
key];
};
//定义拖拽函数对象
var
startDrag =
function(
bar,
target,
callback){
if(
getCss(
target,
"left") !==
"auto"){
params.
left =
getCss(
target,
"left");
}
if(
getCss(
target,
"top") !==
"auto"){
params.
top =
getCss(
target,
"top");
}
//o鏄Щ鍔ㄥ璞�
bar.
onmousedown =
function(
event){
params.
flag =
true;
if(!
event){
event =
window.
event;
//
bar.
onselectstart =
function(){
return
false;
}
}
var
e =
event;
params.
currentX =
e.
clientX;
params.
currentY =
e.
clientY;
};
document.
onmouseup =
function(){
params.
flag =
false;
if(
getCss(
target,
"left") !==
"auto"){
params.
left =
getCss(
target,
"left");
}
if(
getCss(
target,
"top") !==
"auto"){
params.
top =
getCss(
target,
"top");
}
};
document.
onmousemove =
function(
event){
var
e =
event ?
event:
window.
event;
if(
params.
flag){
var
nowX =
e.
clientX,
nowY =
e.
clientY;
var
disX =
nowX -
params.
currentX,
disY =
nowY -
params.
currentY;
target.
style.
left =
parseInt(
params.
left) +
disX +
"px";
target.
style.
top =
parseInt(
params.
top) +
disY +
"px";
if (
typeof
callback ==
"function") {
callback((
parseInt(
params.
left) ||
0) +
disX, (
parseInt(
params.
top) ||
0) +
disY);
}
if (
event.
preventDefault) {
event.
preventDefault();
}
return
false;
}
}
};
var
oBox =
document.
getElementById(
"box");
var
oBar =
document.
getElementById(
"bar");
startDrag(
oBar,
oBox);
<
/
script
>
body
>
html
>