写一个拖动的效果 可是不能正确的拖动 不知道问题在哪里
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <style> 7 body {background-color: black;font: 12px arial;color: #fff;} 8 #container {width: 300px;height: 120px;border: 2px solid white;background-color: #222;/*margin: 20px auto;*/} 9 #head {height: 20px;text-align: right;border-bottom: 2px solid white;padding-right: 10px;color: #fff;cursor: move;} 10 #container p {line-height: 10px;} 11 #container .content {height: 100%;} 12 </style> 13 <script> 14 window.onload = function() { 15 var container = document.getElementById("container"),head = document.getElementById("head"); 16 var bDrag = false; 17 var startXy, endXy, startPosition; 18 19 head.onmousedown = function (event) { 20 var e = event || window.event; 21 bDrag = true; 22 startXy = { x: e.clientX, y: e.clientY };/*鼠标坐标*/ 23 startPosition = { left: container.offsetLeft, top: container.offsetTop };/*开始坐标*/ 24 this.setCapture && this.setCapture(); 25 status(); 26 return false; 27 }; 28 document.onmouseup = window.onblur = head.onlosecapture = function () { 29 bDrag = false; 30 status(); 31 head.releaseCapture && head.releaseCapture(); 32 return false; 33 }; 34 35 document.onmousemove = function (event) { 36 if (!bDrag) {return false;} 37 var e = event || window.event; 38 endXy = { x: e.clientX, y: e.clientY };/*结束鼠标坐标*/ 39 container.style.left = ((startXy.x < endXy.x) ? (startPosition.left + (endXy.x - startXy.x)) : 40 (startPosition.left - (startXy.x - endXy.x))) + "px"; 41 container.style.top = (startXy.y < endXy.y) ? (startPosition.top + (endXy.y - startXy.y)) + "px" : 42 (startPosition.top - (startXy.y - endXy.y)) + "px"; 43 44 status(); 45 return false; 46 }; 47 function status() { 48 document.getElementById("spanFlag").innerHTML = bDrag; 49 document.getElementById("spanTop").innerHTML = container.offsetTop; 50 document.getElementById("spanLeft").innerHTML = container.offsetLeft; 51 } 52 status(); 53 } 54 </script> 55 </head> 56 <body> 57 <div id="container"> 58 <h2 id="head">回放</h2> 59 <p><strong>Drag:</strong><span id="spanFlag"></span> </p> 60 <p><strong>OffsetTop:</strong><span id="spanTop"></span></p> 61 <p><strong>OffsetLeft:</strong><span id="spanLeft"></span></p> 62 </div> 63 </body> 64 </html>