javascript 拖动对象
来源:互联网 发布:淘宝网打底牛仔裤女 编辑:程序博客网 时间:2024/05/21 09:00
<html><head> <script type="text/javascript"> <!-- var currentMoveObj = null; // 当前拖动对象 var rel_left; var rel_top; function f_mousedown(obj) { // 当对象被按下时,记录该对象 currentMoveObj = obj; // setCapture() 可以让对象捕捉到鼠标事件,跟随着鼠标做出响应 currentMoveObj.setCapture(); // 设置对象的定位方式为absolute,便于计算拖动位置 currentMoveObj.style.position = "absolute"; // 记录鼠标按下时距离被移动物体的左上角的偏移量,以便在移动鼠标的时候正确计算位移 rel_left = event.x - currentMoveObj.style.pixelLeft; rel_top = event.y - currentMoveObj.style.pixelTop; //alert(rel_left + ", " + rel_right); window.document.attachEvent('onmouseup', function () { // releaseCapture() 执行和 setCapture() 相反的操作 currentMoveObj.releaseCapture(); currentMoveObj = null; }); } function f_mousemove(obj) { if (currentMoveObj != null) { // currentMoveObj.style.pixelLeft = event.x - rel_left; currentMoveObj.style.pixelTop = event.y - rel_top; } } //--> </script></head><body><table id="myTable" border="1" style="position:absolute; left:50; top:50;" onmousedown="f_mousedown(this)" onmousemove="f_mousemove(this)"><tr><td bgcolor="#cccccc" align="center" style="cursor:move;">title1</td></tr> <tr> <td align="center" height="60">content</td> </tr></table> <table width="100" border="1" onselectstart="return false" style="position:absolute; left:350; top:250;" onmousedown="f_mousedown(this)" onmousemove="f_mousemove(this)"> <tr> <td bgcolor="#cccccc" align="center" style="cursor:move;">title2</td> </tr> <tr> <td align="center" height="60">content</td> </tr> </table></body><html>