--- title: Element.setPointerCapture() slug: Web/API/Element/setPointerCapture tags: - API - DOM - Element translation_of: Web/API/Element/setPointerCapture ---
{{APIRef("DOM")}}
{{domxref("Element")}}接口的setPointerCapture()
方法用于将特定元素指定为未来指针事件的捕获目标。指针的后续事件将以捕获元素为目标,直到捕获被释放(通过{{domxref("Element.releasePointerCapture()")}})。
targetElement.setPointerCapture(pointerId);
pointerId
返回void。如果pointerId
不匹配任何当前活动的指针事件,将抛出{{domxref("DOMException")}}。
当您按下它时,此示例在 {{HtmlElement("div")}} 上设置指针捕获。这使您可以滑动元素,即使指针移动到其边界之外也是如此。
<div id="slider">SLIDE ME</div>
div { width: 140px; height: 50px; display: flex; align-items: center; justify-content: center; background: #fbe; }
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;
{{EmbedLiveSample("示例")}}
标准 | 状态 | 备注 |
---|---|---|
{{SpecName('Pointer Events 2','#widl-Element-setPointerCapture-void-long-pointerId', 'setPointerCapture')}} | {{Spec2('Pointer Events 2')}} | 不稳定版本 |
{{SpecName('Pointer Events', '#widl-Element-setPointerCapture-void-long-pointerId', 'setPointerCapture')}} | {{Spec2('Pointer Events')}} | 初版 |
{{Compat("api.Element.setPointerCapture")}}