鼠标捕获(setCapture)作用是将鼠标事件捕获到当前文档的指定的对象——对指定的对象设置鼠标捕获。这个对象会为当前应用程序或整个系统接收所有鼠标事件。
- 所谓鼠标捕获,是指对鼠标事件(onmousedown, onmouseup, onmousemove, onclick, ondblclick, onmouseover, onmouseout)进行捕捉,使在容器内的子对象的鼠标事件均由容器对象触发,因此,只能在容器对象的鼠标事件函数中进行处理。
- 当参数为true时,对鼠标进行捕捉,相反,不捕捉。
- 与这个函数对应,releaseCapture方法释放鼠标捕获,并触发onlosecapture事件。
一、语法
1. MDN()
element.setCapture(retargetToElement);
retargetToElement——If true
, all events are targeted directly to this element; if false
, events can also fire at descendants of this element.
document.releaseCapture()
释放鼠标捕捉——Once mouse capture is released, mouse events will no longer all be directed to the element on which capture is enabled.
2. msdn()
object.setCapture(containerCapture)
- 其中: containerCapture [in, optional]—— Type: Boolean
-
- true (true)——Default. 容器会捕获容器内所有对象的鼠标事件,即容器内的对象不会触发鼠标事件(跟容器外的对象一样)Events originating in a container are captured by the container.
- false (false)——容器不会捕获容器内对象的鼠标事件,即容器内的对象可以正常地触发事件和取消冒泡。Events originating in a container are not captured by the container.
object.setCapture() 当一个object的被 setCapture 后,他的方法将会被继承到整个文档进行捕获。当不需要把方法继承到整个文档捕获时,要用 object.releaseCapture() 来释放.
二、案例——简单拖拽
完整代码
drag example drag me
三、案例——完美拖拽
完整代码
完美拖拽
javascript代码
//鼠标按下, 激活拖拽 oH2.onmousedown = function (event){ var event = event || window.event; bDrag = true; disX = event.clientX - oBox.offsetLeft; disY = event.clientY - oBox.offsetTop; aPos.push({x:oBox.offsetLeft, y:oBox.offsetTop}); this.setCapture && this.setCapture(); return false; }; //拖拽开始 document.onmousemove = function (event){ if (!bDrag) return; var event = event || window.event; var iL = event.clientX - disX; var iT = event.clientY - disY; var maxL = document.documentElement.clientWidth - oBox.offsetWidth; var maxT = document.documentElement.clientHeight - oBox.offsetHeight; iL = iL < 0 ? 0 : iL; iL = iL > maxL ? maxL : iL; iT = iT < 0 ? 0 : iT; iT = iT > maxT ? maxT : iT; oBox.style.marginTop = oBox.style.marginLeft = 0; oBox.style.left = iL + "px"; oBox.style.top = iT + "px"; aPos.push({x:iL, y:iT}) status(); return false; }; //鼠标释放, 结束拖拽 document.onmouseup = window.onblur = oH2.onlosecapture = function (){ bDrag = false; oH2.releaseCapture && oH2.releaseCapture(); status(); }; //阻止冒泡 oA.onmousedown = function (event){ (event || window.event).cancelBubble = true }; //监听状态函数 function status (){ aSpan[0].innerHTML = bDrag; aSpan[1].innerHTML = oBox.offsetTop; aSpan[2].innerHTML = oBox.offsetLeft; }
参考:
- https://developer.mozilla.org/en-US/docs/Web/API/Element.setCapture
- http://msdn.microsoft.com/en-us/library/ie/ms536742%28v=vs.85%29.aspx