Spring Drag Snap
弹簧拖拽吸附
A handle follows the pointer and settles into its nearest docking point with a damped spring when released.
Where to use it
Make discrete positions feel physical in alignment controls, carousels, or draggable panels. Pair the spring with clearly marked stops when users can drag freely but the control has a discrete set of valid values.
Practical example
In an icon editor, a density handle moves along three marked stops. Releasing it near Compact makes the handle briefly overshoot and settle there, and the icon grid uses the compact spacing.
AI prompt
Add Spring Drag Snap to [draggable control]. Capture the pointer, constrain motion to its track, and snap to the nearest stop after release using the release velocity in a damped spring. Preserve direct selection and provide Arrow, Home, and End controls. Snap immediately for reduced motion.
Example code
Save the standalone HTML as a file and open it in your browser. It uses the same code as the preview.
View HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Spring Drag Snap</title>
<style>
:root {
color-scheme: dark;
--demo-bg: #171629;
--demo-ink: #f8f5ff;
--demo-accent: #b9a6ff;
--demo-muted: #bfbbd3;
font-family: system-ui, sans-serif;
color: var(--demo-ink);
background: var(--demo-bg);
}
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; min-width: 0; }
button, input { font: inherit; }
.demo {
display: grid;
place-items: center;
align-content: center;
min-height: 100vh;
padding: 14px;
overflow: hidden;
background: radial-gradient(ellipse at 50% 24%, #28233f, var(--demo-bg) 78%);
}
.demo-button {
border: 1px solid #ffffff3d;
border-radius: 7px;
background: #ffffff12;
color: var(--demo-ink);
padding: 6px 11px;
font-size: 12px;
cursor: pointer;
}
:focus-visible {
outline: 2px solid var(--demo-accent);
outline-offset: 3px;
}
.spring-scene {
width: min(100%, 282px); min-height: 134px; border-radius: 14px;
border: 1px solid #61558e; background: #282049; padding: 10px 12px 9px;
}
.spring-title { margin: 0; color: #efeaff; font-weight: 650; font-size: 11px; }
.spring-track {
height: 43px; margin-top: 8px; position: relative;
border: 1px solid #655291; border-radius: 8px; background: #1b1531;
}
.spring-notches {
position: absolute; inset: 0 10%; display: flex; align-items: center; justify-content: space-between;
}
.spring-notches::before { content: ''; position: absolute; inset: calc(50% - 1px) 0 auto; height: 2px; background: #55417f; }
.spring-notches i { position: relative; width: 7px; height: 7px; background: #907bbb; border-radius: 50%; }
.spring-thumb {
position: absolute; top: 50%;
left: clamp(16px, 10% + var(--position, 1) * 40%, 100% - 16px);
transform: translate(-50%, -50%); display: grid; place-items: center;
width: 32px; height: 30px; border: 1px solid #dcd0fd; border-radius: 7px;
background: linear-gradient(145deg, #ded0fd, #ad91e7); color: #472c75;
cursor: grab; touch-action: none; user-select: none; box-shadow: 0 2px 8px #0007;
}
.spring-thumb[data-dragging] { cursor: grabbing; }
.spring-thumb span { pointer-events: none; font-size: 12px; letter-spacing: -4px; margin-right: 3px; }
.spring-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; margin-top: 9px; }
.spring-position {
min-height: 25px; border-radius: 6px; color: #e6dbfb; font-size: 10px;
border: 1px solid #66568f; background: #312755; cursor: pointer; padding: 2px;
}
.spring-position[aria-pressed="true"] { color: #2c1a4a; background: #deccff; border-color: #deccff; font-weight: 700; }
</style>
</head>
<body>
<main class="demo">
<div class="spring-scene">
<p class="spring-title" id="spring-title">Focus position</p>
<div class="spring-track">
<span class="spring-notches" aria-hidden="true"><i></i><i></i><i></i></span>
<div class="spring-thumb" role="slider" tabindex="0" aria-labelledby="spring-title" aria-valuemin="0" aria-valuemax="2" aria-valuenow="1" aria-valuetext="Center" data-position="1" data-testid="spring-drag-slider"><span aria-hidden="true">⋮⋮</span></div>
</div>
<div class="spring-actions" role="group" aria-labelledby="spring-title">
<button class="spring-position" type="button" data-index="0" aria-pressed="false">Left</button><button class="spring-position" type="button" data-index="1" aria-pressed="true">Center</button><button class="spring-position" type="button" data-index="2" aria-pressed="false">Right</button>
</div>
</div>
</main>
<script>
const track = document.querySelector('.spring-track');
const thumb = document.querySelector('.spring-thumb');
const positions = Array.from(document.querySelectorAll('.spring-position'));
const labels = ["Left","Center","Right"];
const reduced = matchMedia('(prefers-reduced-motion: reduce)');
const clamp = (position) => Math.min(2, Math.max(0, position));
let position = 1;
let target = 1;
let animationFrame = 0;
let drag;
function render() {
const nearest = Math.round(clamp(position));
thumb.style.setProperty('--position', String(position));
thumb.dataset.position = String(position);
if (thumb.getAttribute('aria-valuenow') === String(nearest)) return;
thumb.setAttribute('aria-valuenow', String(nearest));
thumb.setAttribute('aria-valuetext', labels[nearest]);
positions.forEach((button, index) => button.setAttribute('aria-pressed', String(nearest === index)));
}
function settle(next, speed = 0) {
cancelAnimationFrame(animationFrame);
target = clamp(next);
if (reduced.matches) {
position = target;
render();
return;
}
let previous = performance.now();
let velocity = Math.min(5, Math.max(-5, speed));
function tick(now) {
let remaining = Math.min((now - previous) / 1000, 0.036);
previous = now;
while (remaining > 0) {
const step = Math.min(remaining, 0.008);
const acceleration = 178 * (target - position) - 18 * velocity;
velocity += acceleration * step;
position += velocity * step;
remaining -= step;
}
if (Math.abs(target - position) < 0.003 && Math.abs(velocity) < 0.025) {
position = target;
render();
return;
}
render();
animationFrame = requestAnimationFrame(tick);
}
animationFrame = requestAnimationFrame(tick);
}
thumb.addEventListener('pointerdown', (event) => {
if (drag || event.button !== 0) return;
cancelAnimationFrame(animationFrame);
thumb.setPointerCapture(event.pointerId);
drag = { id: event.pointerId, x: event.clientX, start: position, lastPosition: position, time: event.timeStamp, speed: 0 };
thumb.toggleAttribute('data-dragging', true);
});
thumb.addEventListener('pointermove', (event) => {
if (!drag || drag.id !== event.pointerId) return;
const distancePerStep = Math.max(1, track.clientWidth * 0.4);
position = clamp(drag.start + (event.clientX - drag.x) / distancePerStep);
const elapsed = Math.max(8, event.timeStamp - drag.time) / 1000;
drag.speed = 0.65 * ((position - drag.lastPosition) / elapsed) + 0.35 * drag.speed;
drag.lastPosition = position;
drag.time = event.timeStamp;
render();
});
function finishDrag(event) {
if (!drag || drag.id !== event.pointerId) return;
const speed = event.type === 'pointerup' && event.timeStamp - drag.time < 65 ? drag.speed : 0;
drag = undefined;
thumb.removeAttribute('data-dragging');
settle(Math.round(clamp(position)), speed);
}
thumb.addEventListener('pointerup', finishDrag);
thumb.addEventListener('pointercancel', finishDrag);
thumb.addEventListener('lostpointercapture', finishDrag);
thumb.addEventListener('keydown', (event) => {
let next;
if (event.key === 'ArrowRight' || event.key === 'ArrowUp') next = target + 1;
if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') next = target - 1;
if (event.key === 'Home') next = 0;
if (event.key === 'End') next = 2;
if (next === undefined || drag) return;
event.preventDefault();
settle(next);
});
positions.forEach((button, index) => button.addEventListener('click', () => {
if (!drag) settle(index);
}));
reduced.addEventListener('change', () => {
if (!drag) settle(target);
});
</script>
</body>
</html>Original example by UI Skills