Pointer Capture Tracks Drag Deltas
Keep pointer events flowing to one element with setPointerCapture: drags continue outside the bounds until releasePointerCapture or pointercancel.
Code
// 拖拽滑块:pointerdown 后接管指针,即使移出元素也能继续跟踪
const knob = document.querySelector('#knob');
let lastX = 0;
knob.addEventListener('pointerdown', (event) => {
// pointer capture:后续 pointermove 都派发给 knob,移出边界不丢事件
knob.setPointerCapture(event.pointerId);
lastX = event.clientX;
knob.dataset.dragging = 'true';
});
knob.addEventListener('pointermove', (event) => {
if (knob.dataset.dragging !== 'true') return;
const delta = event.clientX - lastX;
lastX = event.clientX;
const current = Number(knob.dataset.value || '0');
const next = Math.max(0, Math.min(200, current + delta));
knob.dataset.value = String(next);
knob.style.setProperty('--knob-x', next + 'px');
});
const endDrag = (event) => {
// releasePointerCapture 显式释放;不释放时浏览器也会在 pointerup 自动释放
if (knob.hasPointerCapture(event.pointerId)) {
knob.releasePointerCapture(event.pointerId);
}
knob.dataset.dragging = 'false';
};
knob.addEventListener('pointerup', endDrag);
knob.addEventListener('pointercancel', endDrag);
// 触摸设备需配合 CSS touch-action: none,否则滚动手势会吞掉 pointermoveWhat the code does
Count the function endDrag as the entire surface area of Pointer Capture Tracks Drag Deltas.
Caveats
- Uses
document, so it needs a browser context — it will not run as-is in Node without shims. - The guard
knob.dataset.dragging !== 'true'short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The main signature reads const endDrag = (event)
Key statements
knob.addEventListener('pointerdown', (event) => {
// pointer capture:后续 pointermove 都派发给 knob,移出边界不丢事件
knob.setPointerCapture(event.pointerId);
lastX = event.clientX;
knob.dataset.dragging = 'true';
});
knob.addEventListener('pointercancel', endDrag);
knob.addEventListener('pointerup', endDrag);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.
FAQ
- Does Pointer Capture Tracks Drag Deltas run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.