<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script> window.onload = function () { var odiv = document.getElementById('wrap'); odiv.onmousedown = function (ev) { var ev = ev || event; var L1 = ev.clientX - odiv.offsetLeft var T1 = ev.clientY - odiv.offsetTop; var oadd = document.createElement('div'); if(odiv.setCapture) { odiv.setCapture(); } odiv.appendChild(oadd); document.onmousemove = function (ev) { var ev = ev || event; var L2 = ev.clientX - odiv.offsetLeft var T2 = ev.clientY - odiv.offsetTop; L2 = L2 < 0 ? 0 : L2; L2 = L2 > odiv.clientWidth ? odiv.clientWidth : L2; T2 = T2 < 0 ? 0 : T2; T2 = T2 > odiv.clientHeight ? odiv.clientHeight: T2; oadd.style.cssText = 'border: 1px solid red;' oadd.style.left = L1 < L2 ?(L1 + 'px'):(L2 + 'px'); oadd.style.top = T1 > T2 ? (T2 + 'px'):(T1 + 'px'); oadd.style.width = Math.abs(Math.abs(L1 - L2)-2) + 'px'; oadd.style.height = Math.abs(Math.abs(T1 - T2)-2) + 'px'; }; document.onmouseup = function () { document.onmousemove = document.onmousedown = null; if(odiv.releaseCapture) { odiv.releaseCapture(); } } return false; }; }; </script> <style> body { margin:0px; padding:0px; } #wrap { 700px; height: 500px; border: 1px solid #000; margin: 60px auto 10px; position: relative; } #wrap div{ position:absolute; } p { text-align: center; margin: 0px; padding: 10px; } </style> </head> <body> <div id="wrap"> </div> <p>可以在上面的方框中任意拉出方块</p> </body> </html>