电脑附件的画图工具里,我们可以在画布上用鼠标随意选取矩形的选区.
自己用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" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>画方块-sunshinegirl</title> <style type="text/css"> .div1{ position: absolute; left:0; top:0; border:1px solid #000; background-color:#EFEFEF; } </style> <script> window.onload=function(){ document.onmousedown=function(ev){ ev=ev||event; //鼠标按下时存一下此时left和top值 var startLeft=ev.clientX, startTop=ev.clientY; //定义四个变量 var smallLeft,bigLeft,smallTop,bigTop; //生成一个div var oDiv=document.createElement("div"); //鼠标移动时 document.onmousemove=function(ev){ ev=ev||event; //存一下当前left和top var currentLeft=ev.clientX, currentTop=ev.clientY; //比较四个值,作为方块的left,top if(startLeft<currentLeft){ smallLeft=startLeft; bigLeft=currentLeft }else{ smallLeft=currentLeft; bigLeft=startLeft; } if(startTop<currentTop){ smallTop=startTop; bigTop=currentTop; }else{ smallTop=currentTop; bigTop=startTop; } //赋值,加效果 oDiv.style.left=smallLeft+"px"; oDiv.style.top=smallTop+'px'; oDiv.style.width=bigLeft-smallLeft+'px'; oDiv.style.height=bigTop-smallTop+'px'; //加到body里 document.body.appendChild(oDiv); oDiv.className="div1"; } //鼠标抬起时把onmousemove和onmouseup为null document.onmouseup=function(){ document.onmousemove=null; document.onmouseup=null; } return false; } } </script> </head> <body> </body> </html>