使用div實作了選取框效果.
代碼如下
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>myCanvasTest</title>
5 <style type="text/css">
6 #selection{
7 border: 3px red solid;
8 display: none;
9 position: absolute;
10 }
11 *{
12 cursor: crosshair;
13 }
14 </style>
15 </head>
16 <body>
17 <div id="selection"></div>
18 </body>
19 <script type="text/javascript">
20 var selection, //存儲坐标量(友善用)
21 flag = false, //作為是否在滑鼠點選時的移動标記
22 selectionDiv = document.getElementById("selection"); //擷取選取框div對象
23
24 //初始化坐标對象
25 function init () {
26 selection = {
27 top :0,
28 left :0,
29 width :0,
30 height :0
31 };
32 }
33
34 //滑鼠按下,記錄坐标
35 function setLocation (x, y) {
36 selection.left = x;
37 selection.top = y;
38 }
39
40 //滑鼠移動計算距離存入寬高
41 function moveLocation (x, y) {
42 selection.width = selection.left - x;
43 selection.height = selection.top - y;
44 moveIt();
45 }
46
47 //更新div坐标尺寸資訊
48 function moveIt () {
49 console.log(selection);
50 //高度寬度小于0時說明拖拽x,y為正值,如小于0說明拖動為反方向.需重新計算top及left保證拖拽效果
51 selectionDiv.style.top = (selection.height < 0 ?
52 selection.top :
53 selection.top - selection.height)
54 + "px";
55 selectionDiv.style.left = (selection.width < 0 ?
56 selection.left :
57 selection.left - selection.width)
58 + "px";
59 //Math.abs()方法傳回絕對值
60 selectionDiv.style.width = Math.abs(selection.width)
61 + "px";
62 selectionDiv.style.height = Math.abs(selection.height)
63 + "px";
64 }
65
66 //顯示選取框div
67 function showIt () {
68 selectionDiv.style.display = "block";
69 }
70
71 //隐藏選取框div
72 function hideIt () {
73 selectionDiv.style.display = "none";
74 }
75
76 //滑鼠按下觸發事件
77 window.onmousedown = function (e) {
78 var x = e.clientX,
79 y = e.clientY;
80 //初始化坐标對象
81 init();
82 //顯示div對象
83 showIt();
84 //設定top,left值.作為本次拖拽的原點
85 setLocation(x, y);
86 //調用移動方法
87 moveIt();
88 //将标記打開
89 flag = true;
90 }
91
92 //滑鼠移動時觸發
93 window.onmousemove = function (e) {
94 var x = e.clientX,
95 y = e.clientY;
96 //當标記開啟時,觸發事件
97 if(flag)
98 moveLocation(x, y);
99 }
100
101 //滑鼠擡起,觸發事件,将div隐藏,清除坐标對象,關閉标記
102 window.onmouseup = function (e) {
103 //隐藏div
104 hideIt();
105 //清除坐标資訊
106 init();
107 //關閉标記
108 flag = false;
109 }
110
111 </script>
112 </html>
感覺在編碼的時候.卡在了x,y都為負值的地方.
為了保證在x,y都為負值時還有拖拽效果.必須要将div的位置移動.
看起來就像拖拽一樣.實則在更新大小的同時更新了div的坐标位置