Element.setPointerCapture()

Element接口的setPointerCapture() 方法用于将特定元素指定为未来指针事件的捕获目标。指针的后续事件将以捕获元素为目标,直到捕获被释放(通过Element.releasePointerCapture())。

一旦设置了pointer capture,  pointerover, pointerout pointerenter, 和pointerleave  事件将不会被触发,直到越过设置了capture的元素的边界。这是因为其他元素将不能再作为pointer事件的目标了。这会影响到这些事件在其他元素上的触发。

指针捕获概述

指针捕获允许一个特定的指针事件(PointerEvent) 事件从一个事件触发时候的目标重定位到另一个目标上。这个功能可以确保一个元素可以持续的接收到一个pointer事件,即使这个事件的触发点已经移出了这个元素(比如,在滚动的时候)。

语法

targetElement.setPointerCapture(pointerId);

参数

pointerId
PointerEvent 对象的pointerId

返回值

返回void。如果pointerId不匹配任何当前活动的指针事件,将抛出DOMException

示例

当您按下它时,此示例在 <div> 上设置指针捕获。这使您可以滑动元素,即使指针移动到其边界之外也是如此。

HTML

<div id="slider">SLIDE ME</div>

CSS

div {
  width: 140px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fbe;
}

JavaScript

function beginSliding(e) {
  slider.onpointermove = slide;
  slider.setPointerCapture(e.pointerId);
}

function stopSliding(e) {
  slider.onpointermove = null;
  slider.releasePointerCapture(e.pointerId);
}

function slide(e) {
  slider.style.transform = `translate(${e.clientX - 70}px)`;
}

const slider = document.getElementById('slider');

slider.onpointerdown = beginSliding;
slider.onpointerup = stopSliding;

结果

规范

标准 状态 备注
Pointer Events – Level 2
setPointerCapture
Working Draft 不稳定版本
Pointer Events
setPointerCapture
Recommendation 初版

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
setPointerCaptureChrome Full support 55Edge Full support 12Firefox Full support 59
Full support 59
Full support 41
Disabled
Disabled From version 41: this feature is behind the dom.w3c_pointer_events.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE Full support 11
Full support 11
Full support 10
Prefixed
Prefixed Implemented with the vendor prefix: ms
Opera Full support 42Safari No support NoWebView Android Full support 55Chrome Android Full support 55Firefox Android No support No
No support No
Full support 41
Disabled
Disabled From version 41: this feature is behind the dom.w3c_pointer_events.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Full support 42Safari iOS No support NoSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.
Requires a vendor prefix or different name for use.
Requires a vendor prefix or different name for use.

参见