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

javascript移动对象问题
DragMe.js代码
var x,y;

var z,down=false;

function init(e){ 
e.setCapture(); //设置属于当前对象的鼠标捕捉 
z=e.style.zIndex; //获取对象的z轴坐标值 
//设置对象的z轴坐标值为10000,确保当前层显示在最前面 
e.style.zIndex=10000; 
x=event.clientX; //获取鼠标指针位置相对于触发事件的对象的X坐标 
y=event.clientY; //获取鼠标指针位置相对于触发事件的对象的Y坐标 
down=true; //布尔值,判断鼠标是否已按下,true为按下,false为未按下 


function moveit(e){ 
//判断鼠标已被按下且onmouseover和onmousedown事件发生在同一对象上 
//if(down&&event.srcElement==obj){ 
if(down){
  with(e.style){ 
  posLeft=event.clientX-x;
  posTop=event.clientY-y;
  } 



function stopdrag(e){ 
//onmouseup事件触发时说明鼠标已经松开,所以设置down变量值为false 
e.style.zIndex=z; //还原对象的Z轴坐标值 
e.releaseCapture(); //释放当前对象的鼠标捕捉 
down=false;
}

运行页代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> neverOnlineMap - http://www.never-online.net </title>
<script type="text/javascript" language="javascript" src="Scripts/DragMe.js"></script>
<style type="text/css">

.dragme{position:relative; cursor:hand;}
.doit{position:relative; cursor:hand;}
</style>

</head>
<body>
<img onmousedown="init(this);" onmousemove="moveit(this);" onmouseup="stopdrag(this);" class="doit" name="fddd" src="images/btn_34_off.gif" id="img34" alt="鹰眼" title="鹰眼" />
<!--把下列代码加到body区域内,可以给自己的连接加上: class="dragme" -->

<div align="center">
<div style="width:0" id="test" onmousedown="init(this);" onmousemove="moveit(this);" onmouseup="stopdrag(this);" class="doit" >
<table border='1' cellpading='0' cellspacing='0'>
<tr>
<td align='center'>
<img id='GisImage' src="http://www.dzend.com/images/icons/16.gif" hspace='0px' vspace='0px'/>
</td>
</tr>
<tr>
<td id='GisLabel'>4535kjsdfklsjd342543</td>
</tr>
</table>
</div>
<div style='width:0;height:0'class='dragme'>
<table border='0' cellpading='0' cellspacing='0'>
<tr>
<td align='center'>
<img id='GisImage1' hspace='0px' vspace='0px' style='cursor:hand' />
</td>
</tr>
<tr>
<td id='GisLabel1'>3456456</td>
</tr>
</table>
</div>
<img src="http://www.dzend.com/images/icons/16.gif" class="dragme"><br><br>

<img src="http://www.dzend.com/images/icons/22.gif" class="dragme">

</div>

<p>

<font>用鼠标可以拖动图片<br>

by <a href="http://www.dzend.com">dzend</a></font>

</p>
<div onmousedown="init(this);" onmousemove="moveit(this);" onmouseup="stopdrag(this);" class="doit" style='position:absolute;left:0px;top:0px;overflow:auto;width:245px;height:100px'>
<div class="query" >81&nbsp;&nbsp;清华小学
</div>
<div class="query">104&nbsp;&nbsp;明德小学
</div>
<div class="query">2