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

JavaScript实现鼠标拖拽的具体实例
JavaScript实现鼠标拖拽的具体实例
2010-12-01 17:23

?实现鼠标拖拽详细的例子如下:完整复制可查看其效果
<html>
<head>
??? <title>测试鼠标拖动效果</title>
???? <script>
?????? var move=false;
?????? var x;
?????? var y;
?????? function startDrag(target,dragObject){
???????? if(event.button==1){
??????????? var dragObj=document.getElementById(dragObject);
??????????? target.setCapture();
??????????? target.style.backgroundColor="#ccc";
??????????? x=event.clientX-parseInt(dragObj.style.left);
??????????? y=event.clientY-parseInt(dragObj.style.top);
???????????? move=true;
???????? }
?????? }
?????? function drag(dragObject){
??????? //alert("drag");
????????? if(move){
??????????? var dragObj=document.getElementById(dragObject);
??????????? dragObj.style.left=event.clientX-x;
??????????? dragObj.style.top=event.clientY-y;
????????? }
?????? }
?????? function stopDrag(target,dragObject){
????????? var dragObj=document.getElementById(dragObject);
????????? target.style.backgroundColor="#1a37a4";
???????? target.releaseCapture();
?????? }
???? </script>
</head>
<body>
???? <div id="targetObj" style="width:300px;position:absolute;top:10px;left:20px;z-index:10;" >
???????? <table width="100%">
?????????? <tr>
????????????? <td style="width:100%;background-color:#1a37a4;height:30px;cursor:move;" onmousedown="startDrag(this,'targetObj');" onmousemove="drag('targetObj');" onmouseup="stopDrag(this,'targetObj');">
???????????????? <font color="#ffffff">ALI_ZHEZHE Area</font>
????????????? </td>
?????????? </tr>
?????????? <tr>
????????????? <td style="width:100%;background-color:#ffffff;height:100px;text-align:center;">
??????????????? Welcome to Ali_zhezhe's area!
????????????? <td>
?????????? </tr>
???????? </table>
???? </div>
<body>
</html>