js 模拟鼠标绘制方块
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> *{margin:0;padding:0;} #box1{width:500px;height:500px;border:1px solid #000;position:absolute;left:400px;} .cBox{border:1px solid #0C6; width:30px;position:absolute;} </style> <script> window.onload = function(){ var oDiv = document.getElementById('box1'); oDiv.onmousedown = function(ev){ var ev = ev || event; var initX = ev.clientX; var initY = ev.clientY; var cDiv = document.createElement('div'); cDiv.className = 'cBox'; cDiv.style.left = (initX-oDiv.offsetLeft)+'px'; cDiv.style.top = (initY)+'px'; oDiv.appendChild(cDiv); document.onmousemove = function(ev){ var ev = ev || event; var disX = 0; if(ev.clientX >(oDiv.offsetLeft + oDiv.offsetWidth)){ disX = oDiv.offsetLeft + oDiv.offsetWidth; }else{ disX = ev.clientX; } var disY = 0; if(ev.clientY >(oDiv.offsetTop + oDiv.offsetHeight)){ disY = oDiv.offsetTop + oDiv.offsetHeight; }else{ disY = ev.clientY; } var cBoxWidth = disX - initX-2; /*需要减去cDiv的两个边框*/ var cBoxHeight = disY - initY-2; cDiv.style.width = cBoxWidth+'px'; cDiv.style.height = cBoxHeight+'px'; }; document.onmouseup = function(){ document.onmousemove = document.onmouseup = null; }; return false; }; }; </script> </head> <body style="2000px;"> <div id='box1'> </div> </body> </html>