实现鼠标框选效果的代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!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=gbk"> <title>拉框</title> </head> <body> <!-- <div id='lay1' onmousedown='down(event)' onmouseup='up(event)' onmousemove='move(event)' style="top:30px;left:30px;width:400px;height:400px;visibility:visible;border:solid 1px blue;"> </div> --> <div id='rect' style='border:dotted 1px black;position:absolute;'></div> <script language="javascript"> // 是否需要(允许)处理鼠标的移动事件,默认识不处理background-color: #FF99FF var select = false; var rect = document.getElementById("rect"); // 设置默认值,目的是隐藏图层 rect.style.width = 0; rect.style.height = 0; rect.style.visibility = 'hidden'; //让你要画的图层位于最上层 rect.style.zIndex = 1000; // 记录鼠标按下时的坐标 var downX = 0; var downY = 0; // 记录鼠标抬起时候的坐标 var mouseX2=downX; var mouseY2=downY; //处理鼠标按下事件 function down(event) { // 鼠标按下时才允许处理鼠标的移动事件 select = true; //让你要画框的那个图层显示出来 rect.style.visibility = 'visible'; // 取得鼠标按下时的坐标位置 downX = event.clientX; downY = event.clientY; //设置你要画的矩形框的起点位置 rect.style.left = downX; rect.style.top = downY; rect.style.width = "0px"; rect.style.height = "0px"; } //鼠标抬起事件 function up(event) { //鼠标抬起,就不允许在处理鼠标移动事件 select = false; //隐藏图层 rect.style.visibility = 'hidden'; } //鼠标移动事件,最主要的事件 function move(event) { // 取得鼠标移动时的坐标位置 mouseX2 = event.clientX; mouseY2 = event.clientY; // 设置拉框的大小 document.title=[mouseX2 , downX] rect.style.width = Math.abs( mouseX2 - downX ); rect.style.height = Math.abs( mouseY2 - downY ); /* 这个部分,根据你鼠标按下的位置,和你拉框时鼠标松开的位置关系,可以把区域分为四个部分,根据四个部分的不同, 我们可以分别来画框,否则的话,就只能向一个方向画框,也就是点的右下方画框. */ if(select) { //rect.style.visibility = 'visible'; // A part if(mouseX2<downX&&mouseY2<downY ) { rect.style.left = mouseX2; rect.style.top = mouseY2 ; } // B part if(mouseX2>downX &&mouseY2<downY) { rect.style.left = downX ; rect.style.top = mouseY2; } // C part if(mouseX2<downX &&mouseY2>downY) { rect.style.left = mouseX2; rect.style.top = downY ; } // D part if(mouseX2>downX&&mouseY2>downY) { rect.style.left = downX ; rect.style.top = downY; } } /* 这两句代码是最重要的时候,没有这两句代码,你的拉框,就只能拉框,在鼠标松开的时候, 拉框停止,但是不能响应鼠标的mouseup事件.那么你想做的处理就不能进行. 这两句的作用是使当前的鼠标事件不在冒泡,也就是说,不向其父窗口传递,所以才可以相应鼠标抬起事件, 这个部分我也理解的不是特别的清楚,如果你需要的话,你可以查资料.但是这两句话确实最核心的部分, 为了这两句话,为了实现鼠标拉框,我搞了几天的时间. */ window.event.cancelBubble = true; window.event.returnValue = false; } document.onmousedown=function() { down(event); } document.onmousemove=function() { move(event); } document.onmouseup=function() { up(event); } </script> </body> </html>
这个代码在开发某些编辑器的时候有用。