弹簧拖拽吸附
Spring Drag Snap
滑块跟随指针移动,松手后带着拖动速度回弹,稳定在最近的吸附点。
适用场景
用于对齐控件、轮播或可拖拽面板,让用户感受到可选位置和吸附边界。 允许连续拖动但只接受几个固定值时,把停靠点标清楚,松手的回弹会说明最终采用了哪个值。
应用示例
图标编辑器的密度滑柄有三个标记位置。在「紧凑」附近松手,滑柄轻微越过标记后回到那里,图标网格随即采用紧凑间距。
AI 提示词
给【可拖动控件】添加弹簧拖拽吸附。捕获指针并将位置限制在轨道,松手时把释放速度带入阻尼弹簧,吸附到最近刻度。提供直接点选、方向键和 Home/End 按键操作,减少动态效果模式直接跳到目标位置。
示例代码
保存为 HTML 文件后,用浏览器打开即可运行。代码与页面里的演示一致。
查看 HTML
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>弹簧拖拽吸附</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">调整焦点位置</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="居中" 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">靠左</button><button class="spring-position" type="button" data-index="1" aria-pressed="true">居中</button><button class="spring-position" type="button" data-index="2" aria-pressed="false">靠右</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 = ["靠左","居中","靠右"];
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>UI Skills 原创示例