刚学js的时候,闲着没事,自己练习做的玩的
<script type="text/javascript"> var layerObj = document.getElementById("moveLayer"); layerObj.style.cursor = "move"; layerObj.style.position = "absolute"; var mousePosX; var mousePosY; var layerPosX; var layerPosY; var chkButton; function setDivMousePos(e, eventT) { chkButton = -1; eventT = eventT || window.event; if (eventT.button != 2) { chkButton = 10; } if (chkButton == 10) { mousePosX = eventT.clientX + document.body.scrollLeft; mousePosY = eventT.clientY + document.body.scrollTop; if (e.style.left == '') { layerPosX = 0; } else { layerPosX = parseInt(e.style.left); } if (e.style.top == '') { layerPosY = 0; } else { layerPosY = parseInt(e.style.top); } } } function moveLayerFunc(e, et) { if (chkButton == 10) { et = et || window.event; e.style.top = layerPosY + (et.clientY + document.body.scrollTop - mousePosY) + "px"; e.style.left = layerPosX + (et.clientX + document.body.scrollLeft - mousePosX) + "px"; } } layerObj.onmousedown = function (et) { setDivMousePos(this, et); } layerObj.onmousemove = function (et) { moveLayerFunc(this, et); } layerObj.onmouseup = function () { chkButton = -1; } layerObj.onmouseout = function () { chkButton = -1; } </script>
以上是javascript代码,只需要将你想要移动的 div 的 id 设置为 moveLayer 就OK了。