日期:2014-05-16  浏览次数:20301 次

一个和 层拖动及类 相关的问题
<body>
<div   id= "d1 "   style= "   position:absolute;   top:10px;   left:10px;   border-color:#0000FF;   background-color:#00FF00;   border-style:solid;   height:60px;   width:60px; "> 鼠标拖拽1 </div>
<div   id= "d2 "   style= "   position:absolute;   top:10px;   left:200px;   border-color:#0000FF;   background-color:#00FF00;   border-style:solid;   height:60px;   width:60px; "> 鼠标拖拽2 </div>

</body>
<script   language= "javascript ">

function   g(a)
{
di=document.getElementById(a);
var   sx,sy;

function   move()
{
di.style.top=event.clientY-sy+ 'px ';
di.style.left=event.clientX-sx+ 'px ';

}
function   stopM()
{
di.onmousemove=null;
//this.sx=0;this.sy=0;
}
function   obj()
{
sy=event.clientY-Number(di.style.top.substr(0,di.style.top.indexOf( 'px ')));//计算点击时鼠标座标与div层顶点座标差
sx=event.clientX-Number(di.style.left.substr(0,di.style.left.indexOf( 'px ')));
di.onmousemove=move;
di.onmouseup=stopM;
}
di.onmousedown=obj;
}

a=new   g( "d1 ");
b=new   g( "d2 ");
</script>
</html>

初学script,请高手帮忙找错.

------解决方案--------------------
...建议到网上搜一个关于层拖动的例子,有很多,自己看下。你这写的....
------解决方案--------------------
闭包:

<html>

<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=gb2312 ">
<title> 新建网页 1 </title>
</head>

<body>
<div id= "d1 " style= " position:absolute; top:10px; left:10px; border-color:#0000FF; background-color:#00FF00; border-style:solid; height:60px; width:60px; "> 鼠标拖拽1 </div>
<div id= "d2 " style= " position:absolute; top:10px; left:200px; border-color:#0000FF; background-color:#00FF00; border-style:solid; height:60px; width:60px; "> 鼠标拖拽2 </div>

</body>
<script language= "javascript ">

function g(a)
{
di=document.getElementById(a);
var sx,sy;

function move(di)
{
return function(){
di.style.top=event.clientY-sy+ 'px ';
di.style.left=event.clientX-sx+ 'px ';
}
}
function stopM(di)
{
return function(){
di.onmousemove=null;
//this.sx=0;this.sy=0;
}
}
function obj(di)
{
return function(){
sy=event.clientY-Number(di.style.top.substr(0,di.style.top.indexOf( 'px ')));//计算点击时鼠标座标与div层顶点座标差
sx=event.clientX-Number(di.style.left.substr(0,di.style.left.indexOf( 'px ')));
di.onmousemove=move(di);
di.onmouseup=stopM(di);
}
}
di.onmousedown=obj(di);
}

a=new g( "d1 ");
b=new g( "d2 ");
</script>
</html>