javascript鼠标拖动页面对象
该例子转帖自《JAVASCRIPT 王者归来》
js文件
//当前拖动对象
var currentMoveObj = null;
var relLeft;
var relTop;
function f_down(obj)
{
currentMoveObj = obj;
//让对象捕捉鼠标事件,跟随鼠标做出响应
currentMoveObj.setCapture();
currentMoveObj.style.position = "absolute";
relLeft = event.x - currentMoveObj.style.pixelLeft;
relTop = event.y - currentMoveObj.style.pixelTop;
}
window.document.attachEvent('onmouseup', function()
{
if (currentMoveObj != null)
{
currentMoveObj.releaseCapture();
currentMoveObj = null;
}
else
{
}
});
function f_move(obj)
{
if (currentMoveObj != null)
{
currentMoveObj.style.pixelLeft = event.x - relLeft;
currentMoveObj.style.pixelTop = event.y - relTop;
}
}
var currentMoveObj = null;
var relLeft;
var relTop;
function f_down(obj)
{
currentMoveObj = obj;
//让对象捕捉鼠标事件,跟随鼠标做出响应
currentMoveObj.setCapture();
currentMoveObj.style.position = "absolute";
relLeft = event.x - currentMoveObj.style.pixelLeft;
relTop = event.y - currentMoveObj.style.pixelTop;
}
window.document.attachEvent('onmouseup', function()
{
if (currentMoveObj != null)
{
currentMoveObj.releaseCapture();
currentMoveObj = null;
}
else
{
}
});
function f_move(obj)
{
if (currentMoveObj != null)
{
currentMoveObj.style.pixelLeft = event.x - relLeft;
currentMoveObj.style.pixelTop = event.y - relTop;
}
}
页面文件
<div>
<div style="top: 100px; left: 100px; position: absolute">
<table id="table" style="width: 500px; background-color: Aqua" onmousemove="f_move(this)" onmousedown="f_down(this)">
<tr style=" cursor:move" >
<td>
dsadsada
</td>
<td>
dsadsadas
</td>
<td>
dasdasdas
</td>
</tr>
<tr>
<td>
ddasdas
</td>
<td>
dasdas
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<div style="top: 100px; left: 100px; position: absolute">
<table id="table" style="width: 500px; background-color: Aqua" onmousemove="f_move(this)" onmousedown="f_down(this)">
<tr style=" cursor:move" >
<td>
dsadsada
</td>
<td>
dsadsadas
</td>
<td>
dasdasdas
</td>
</tr>
<tr>
<td>
ddasdas
</td>
<td>
dasdas
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</div>
</div>