06下に投げるように閉じるライトボックス
下方向にドラッグして指を離した瞬間、最後の移動速度が計算され、十分速く振り払った時だけ画面外へ弾かれるように閉じ、遅い場合は元の位置に戻る。
使いどころモバイルの写真ビューアー、ストーリー形式の画像表示
pointer velocityspringBack()translate()

<main class="stage">
<div class="scene is-demo" id="scene">
<ul class="grid" id="grid">
<li><button class="thumb" id="thumb0" type="button" aria-haspopup="dialog"><span class="thumbImg"></span></button></li>
</ul>
<div class="backdrop" id="backdrop"></div>
<div class="lightbox" id="lightbox" role="dialog" aria-modal="true" aria-hidden="true" aria-label="写真を投げて閉じる">
<span class="fullImg" id="fullImg"></span>
<p class="dragNote" id="dragNote">下へドラッグして閉じる</p>
<button class="closeBtn" id="closeBtn" type="button">閉じる</button>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 변수 3개
$duration: $dur-base;
$easing: $ease-spring;
$color: $subject-orange-deep;
// 계산 겹: index.html 의 pointermove 가 매 이동마다 세로 속도(px/ms) 를 재고, pointerup 에서
// 그 속도 또는 드래그 거리 비율로 "던졌는지" 판정한다. 던지면 그 속도로 남은 거리를 마저 날아가는
// 시간을 역산하고(flingClose), 아니면 스프링 오버슛 이징으로 되돌아온다(springBack).
@include stage($stage-yellow);
.scene {
position: relative;
width: 320px;
height: 180px;
border-radius: $r-card;
overflow: hidden;
box-shadow: $shadow-raised;
background: linear-gradient(160deg, #fff3c4, $stage-yellow 85%);
}
.grid {
position: absolute;
inset: 0;
margin: 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
.thumb {
appearance: none;
border: none;
background: none;
padding: 0;
cursor: pointer;
&:focus-visible .thumbImg { outline: 2px solid $color; outline-offset: 2px; }
}
.thumbImg {
display: block;
width: 72px;
height: 72px;
border-radius: $r-sm;
box-shadow: $shadow-press;
background: linear-gradient(135deg, $subject-pink, $subject-lilac);
}
.backdrop {
position: absolute;
inset: 0;
background: $subject-ink;
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.lightbox {
position: absolute;
inset: 0;
display: grid;
place-items: center;
visibility: hidden;
overflow: hidden;
}
.fullImg {
display: block;
width: 190px;
height: 130px;
border-radius: $r-card;
background: linear-gradient(135deg, $subject-pink, $subject-lilac 60%, $subject-sky);
touch-action: none;
cursor: grab;
&:active { cursor: grabbing; }
}
.dragNote {
position: absolute;
bottom: $sp-3;
left: 50%;
transform: translateX(-50%);
margin: 0;
font-size: 10px;
font-weight: 700;
color: $subject-cream;
background: rgba(#000, .38);
padding: $sp-1 $sp-3;
border-radius: $r-pill;
pointer-events: none;
}
.closeBtn {
position: absolute;
top: $sp-2;
right: $sp-2;
appearance: none;
border: none;
border-radius: $r-pill;
padding: $sp-1 $sp-3;
font-size: 11px;
font-weight: 600;
color: $subject-ink;
background: rgba($subject-cream, .92);
cursor: pointer;
&:focus-visible { outline: 2px solid $color; outline-offset: 2px; }
}
@media (max-width: 340px) {
.scene { width: 220px; height: 124px; }
.fullImg { width: 140px; height: 96px; }
}
@media (prefers-reduced-motion: reduce) {
// 실사용 경로 적용 — 던지기·스프링백 트윈은 index.html 의 animate() 가 reduce 시 즉시 최종 상태로 처리한다.
.closeBtn, .thumb { transition: none; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #ffd23f;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.scene {
position: relative;
width: 320px;
height: 180px;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
background: linear-gradient(160deg, #fff3c4, #ffd23f 85%);
}
.grid {
position: absolute;
inset: 0;
margin: 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
.thumb {
appearance: none;
border: none;
background: none;
padding: 0;
cursor: pointer;
}
.thumb:focus-visible .thumbImg {
outline: 2px solid #c93000;
outline-offset: 2px;
}
.thumbImg {
display: block;
width: 72px;
height: 72px;
border-radius: 8px;
box-shadow: 0 6px 12px rgba(23, 20, 26, 0.32);
background: linear-gradient(135deg, #ff9ebb, #b9a0ff);
}
.backdrop {
position: absolute;
inset: 0;
background: #17141a;
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.lightbox {
position: absolute;
inset: 0;
display: grid;
place-items: center;
visibility: hidden;
overflow: hidden;
}
.fullImg {
display: block;
width: 190px;
height: 130px;
border-radius: 16px;
background: linear-gradient(135deg, #ff9ebb, #b9a0ff 60%, #6ec8ff);
touch-action: none;
cursor: grab;
}
.fullImg:active {
cursor: grabbing;
}
.dragNote {
position: absolute;
bottom: 12px;
left: 50%;
transform: translateX(-50%);
margin: 0;
font-size: 10px;
font-weight: 700;
color: #fff7e6;
background: rgba(0, 0, 0, 0.38);
padding: 4px 12px;
border-radius: 999px;
pointer-events: none;
}
.closeBtn {
position: absolute;
top: 8px;
right: 8px;
appearance: none;
border: none;
border-radius: 999px;
padding: 4px 12px;
font-size: 11px;
font-weight: 600;
color: #17141a;
background: rgba(255, 247, 230, 0.92);
cursor: pointer;
}
.closeBtn:focus-visible {
outline: 2px solid #c93000;
outline-offset: 2px;
}
@media (max-width: 340px) {
.scene {
width: 220px;
height: 124px;
}
.fullImg {
width: 140px;
height: 96px;
}
}
@media (prefers-reduced-motion: reduce) {
.closeBtn, .thumb {
transition: none;
}
}(function () {
var LIGHTBOX_FLING_VELOCITY_PX_MS = 0.5; // 놓는 순간 이 속도(px/ms) 를 넘으면 던진 것으로 본다
var DRAG_COMMIT_RATIO = 0.32; // 드래그 거리 / 무대 높이 가 이 비율을 넘어도 던진 것으로 본다
var SPRING_BACK_MS = 380;
var LOOP_MS = 2000;
var scene = document.getElementById('scene');
var backdrop = document.getElementById('backdrop');
var lightbox = document.getElementById('lightbox');
var fullImg = document.getElementById('fullImg');
var dragNote = document.getElementById('dragNote');
var closeBtn = document.getElementById('closeBtn');
var thumb = document.getElementById('thumb0');
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var open = false;
var dragging = false;
var dragStartY = 0;
var dragStartX = 0;
var curY = 0;
var curX = 0;
var lastMoveY = 0;
var lastMoveT = 0;
var velocityY = 0;
var timers = [];
function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
// 스프링 오버슛: 목표를 살짝 지나쳤다 되돌아온다
function easeSpringBack(t) { var p = t - 1; return 1 + p * p * (2.7 * p + 1.7); }
function stageH() { return scene.getBoundingClientRect().height; }
function animate(duration, onFrame, onDone, easeFn) {
var ease = easeFn || easeOutCubic;
if (reduce) { onFrame(1); if (onDone) onDone(); return; }
var start = performance.now();
function frame(now) {
var p = clamp((now - start) / duration, 0, 1);
onFrame(ease(p));
if (p < 1) requestAnimationFrame(frame);
else if (onDone) onDone();
}
requestAnimationFrame(frame);
}
function setDrag(x, y, progress) {
fullImg.style.transform = 'translate(' + x.toFixed(2) + 'px,' + y.toFixed(2) + 'px) scale(' + (1 - progress * 0.22).toFixed(4) + ')';
backdrop.style.opacity = (0.78 * (1 - progress)).toFixed(3);
dragNote.style.opacity = (1 - progress * 2).toFixed(3);
}
function openFrom() {
if (open) return;
open = true;
curX = 0; curY = 0;
dragNote.style.opacity = '1';
setDrag(0, 0, 0);
lightbox.style.visibility = 'visible';
lightbox.setAttribute('aria-hidden', 'false');
backdrop.style.visibility = 'visible';
animate(240, function (e) { backdrop.style.opacity = (e * 0.78).toFixed(3); }, function () {
closeBtn.focus({ preventScroll: true });
});
}
function closeLightbox() {
if (!open) return;
lightbox.style.visibility = 'hidden';
lightbox.setAttribute('aria-hidden', 'true');
backdrop.style.visibility = 'hidden';
open = false;
thumb.focus({ preventScroll: true });
}
// 던진 속도로 남은 거리를 마저 날아가게 한다 — 값이 클수록 짧고 빠르게 끝난다
function flingClose(vy) {
var h = stageH();
var fromY = curY;
var fromX = curX;
var targetY = fromY + Math.sign(vy || 1) * (h * 1.4);
var duration = clamp(220 / Math.max(Math.abs(vy), 0.35), 120, 320);
animate(duration, function (e) {
var y = fromY + (targetY - fromY) * e;
var progress = clamp(Math.abs(y) / h, 0, 1);
setDrag(fromX * (1 - e), y, progress);
}, closeLightbox, function (t) { return t; });
}
function springBack() {
var fromX = curX;
var fromY = curY;
animate(SPRING_BACK_MS, function (e) {
setDrag(fromX * (1 - e), fromY * (1 - e), 0);
}, function () {
curX = 0; curY = 0;
closeBtn.focus({ preventScroll: true });
}, easeSpringBack);
}
function human() {
if (scene.classList.contains('is-demo')) {
scene.classList.remove('is-demo');
timers.forEach(function (id) { clearTimeout(id); clearInterval(id); });
timers = [];
}
}
thumb.addEventListener('click', function () { human(); openFrom(); });
closeBtn.addEventListener('click', function () { human(); closeLightbox(); });
backdrop.addEventListener('click', function () { human(); closeLightbox(); });
document.addEventListener('keydown', function (e) {
if (open && e.key === 'Escape') { human(); closeLightbox(); }
});
fullImg.addEventListener('pointerdown', function (e) {
human();
dragging = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
lastMoveY = e.clientY;
lastMoveT = performance.now();
velocityY = 0;
fullImg.setPointerCapture(e.pointerId);
});
fullImg.addEventListener('pointermove', function (e) {
if (!dragging) return;
var now = performance.now();
var dt = now - lastMoveT;
if (dt > 0) velocityY = (e.clientY - lastMoveY) / dt;
lastMoveY = e.clientY;
lastMoveT = now;
curX = e.clientX - dragStartX;
curY = Math.max(0, e.clientY - dragStartY);
var progress = clamp(curY / (stageH() * DRAG_COMMIT_RATIO), 0, 1);
setDrag(curX, curY, progress);
});
function endDrag() {
if (!dragging) return;
dragging = false;
var h = stageH();
var commit = curY > h * DRAG_COMMIT_RATIO || Math.abs(velocityY) > LIGHTBOX_FLING_VELOCITY_PX_MS;
if (commit) flingClose(velocityY);
else springBack();
}
fullImg.addEventListener('pointerup', endDrag);
fullImg.addEventListener('pointercancel', endDrag);
function cycle() {
openFrom();
timers.push(setTimeout(function () {
curX = 6; curY = 0;
var h = stageH();
var fromY = 0;
animate(360, function (e) {
curY = fromY + h * 0.62 * e;
setDrag(curX * (1 - e * 0.4), curY, e * 0.7);
}, function () {
flingClose(LIGHTBOX_FLING_VELOCITY_PX_MS * 1.6);
});
}, 420));
}
if (!reduce) {
cycle();
timers.push(setInterval(function () {
if (scene.classList.contains('is-demo')) cycle();
}, LOOP_MS));
}
})();import { useEffect, useRef } from 'react';
import styles from './CloseVelocityFling.module.scss';
const LIGHTBOX_FLING_VELOCITY_PX_MS = 0.5; // 놓는 순간 이 속도(px/ms) 를 넘으면 던진 것으로 본다
const DRAG_COMMIT_RATIO = 0.32; // 드래그 거리 / 무대 높이 가 이 비율을 넘어도 던진 것으로 본다
const SPRING_BACK_MS = 380;
const LOOP_MS = 2000;
export default function CloseVelocityFling() {
const sceneRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const scene0 = sceneRef.current;
if (!scene0) return undefined;
const backdrop0 = scene0.querySelector<HTMLDivElement>('.' + styles.backdrop);
const lightbox0 = scene0.querySelector<HTMLDivElement>('.' + styles.lightbox);
const fullImg0 = scene0.querySelector<HTMLSpanElement>('.' + styles.fullImg);
const dragNote0 = scene0.querySelector<HTMLParagraphElement>('.' + styles.dragNote);
const closeBtn0 = scene0.querySelector<HTMLButtonElement>('.' + styles.closeBtn);
const thumb0 = scene0.querySelector<HTMLButtonElement>('.' + styles.thumb);
if (!backdrop0 || !lightbox0 || !fullImg0 || !dragNote0 || !closeBtn0 || !thumb0) return undefined;
const scene = scene0;
const backdrop = backdrop0;
const lightbox = lightbox0;
const fullImg = fullImg0;
const dragNote = dragNote0;
const closeBtn = closeBtn0;
const thumb = thumb0;
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
let open = false;
let dragging = false;
let dragStartY = 0;
let dragStartX = 0;
let curY = 0;
let curX = 0;
let lastMoveY = 0;
let lastMoveT = 0;
let velocityY = 0;
let timers: number[] = [];
function clamp(v: number, lo: number, hi: number) { return Math.min(hi, Math.max(lo, v)); }
function easeOutCubic(t: number) { return 1 - Math.pow(1 - t, 3); }
// 스프링 오버슛: 목표를 살짝 지나쳤다 되돌아온다
function easeSpringBack(t: number) { const p = t - 1; return 1 + p * p * (2.7 * p + 1.7); }
function stageH() { return scene.getBoundingClientRect().height; }
function animate(duration: number, onFrame: (e: number) => void, onDone?: () => void, easeFn?: (t: number) => number) {
const ease = easeFn || easeOutCubic;
if (reduce) { onFrame(1); if (onDone) onDone(); return; }
const start = performance.now();
function frame(now: number) {
const p = clamp((now - start) / duration, 0, 1);
onFrame(ease(p));
if (p < 1) requestAnimationFrame(frame);
else if (onDone) onDone();
}
requestAnimationFrame(frame);
}
function setDrag(x: number, y: number, progress: number) {
fullImg.style.transform = 'translate(' + x.toFixed(2) + 'px,' + y.toFixed(2) + 'px) scale(' + (1 - progress * 0.22).toFixed(4) + ')';
backdrop.style.opacity = (0.78 * (1 - progress)).toFixed(3);
dragNote.style.opacity = (1 - progress * 2).toFixed(3);
}
function openFrom() {
if (open) return;
open = true;
curX = 0; curY = 0;
dragNote.style.opacity = '1';
setDrag(0, 0, 0);
lightbox.style.visibility = 'visible';
lightbox.setAttribute('aria-hidden', 'false');
backdrop.style.visibility = 'visible';
animate(240, (e) => { backdrop.style.opacity = (e * 0.78).toFixed(3); }, () => {
closeBtn.focus({ preventScroll: true });
});
}
function closeLightbox() {
if (!open) return;
lightbox.style.visibility = 'hidden';
lightbox.setAttribute('aria-hidden', 'true');
backdrop.style.visibility = 'hidden';
open = false;
thumb.focus({ preventScroll: true });
}
// 던진 속도로 남은 거리를 마저 날아가게 한다 — 값이 클수록 짧고 빠르게 끝난다
function flingClose(vy: number) {
const h = stageH();
const fromY = curY;
const fromX = curX;
const targetY = fromY + Math.sign(vy || 1) * (h * 1.4);
const duration = clamp(220 / Math.max(Math.abs(vy), 0.35), 120, 320);
animate(duration, (e) => {
const y = fromY + (targetY - fromY) * e;
const progress = clamp(Math.abs(y) / h, 0, 1);
setDrag(fromX * (1 - e), y, progress);
}, closeLightbox, (t) => t);
}
function springBack() {
const fromX = curX;
const fromY = curY;
animate(SPRING_BACK_MS, (e) => {
setDrag(fromX * (1 - e), fromY * (1 - e), 0);
}, () => {
curX = 0; curY = 0;
closeBtn.focus({ preventScroll: true });
}, easeSpringBack);
}
function human() {
if (scene.classList.contains(styles['is-demo'])) {
scene.classList.remove(styles['is-demo']);
timers.forEach((id) => { window.clearTimeout(id); window.clearInterval(id); });
timers = [];
}
}
function onThumbClick() { human(); openFrom(); }
function onCloseClick() { human(); closeLightbox(); }
function onBackdropClick() { human(); closeLightbox(); }
function onKeydown(e: KeyboardEvent) {
if (open && e.key === 'Escape') { human(); closeLightbox(); }
}
thumb.addEventListener('click', onThumbClick);
closeBtn.addEventListener('click', onCloseClick);
backdrop.addEventListener('click', onBackdropClick);
document.addEventListener('keydown', onKeydown);
function onPointerDown(e: PointerEvent) {
human();
dragging = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
lastMoveY = e.clientY;
lastMoveT = performance.now();
velocityY = 0;
fullImg.setPointerCapture(e.pointerId);
}
function onPointerMove(e: PointerEvent) {
if (!dragging) return;
const now = performance.now();
const dt = now - lastMoveT;
if (dt > 0) velocityY = (e.clientY - lastMoveY) / dt;
lastMoveY = e.clientY;
lastMoveT = now;
curX = e.clientX - dragStartX;
curY = Math.max(0, e.clientY - dragStartY);
const progress = clamp(curY / (stageH() * DRAG_COMMIT_RATIO), 0, 1);
setDrag(curX, curY, progress);
}
function endDrag() {
if (!dragging) return;
dragging = false;
const h = stageH();
const commit = curY > h * DRAG_COMMIT_RATIO || Math.abs(velocityY) > LIGHTBOX_FLING_VELOCITY_PX_MS;
if (commit) flingClose(velocityY);
else springBack();
}
fullImg.addEventListener('pointerdown', onPointerDown);
fullImg.addEventListener('pointermove', onPointerMove);
fullImg.addEventListener('pointerup', endDrag);
fullImg.addEventListener('pointercancel', endDrag);
function cycle() {
openFrom();
timers.push(window.setTimeout(() => {
curX = 6; curY = 0;
const h = stageH();
const fromY = 0;
animate(360, (e) => {
curY = fromY + h * 0.62 * e;
setDrag(curX * (1 - e * 0.4), curY, e * 0.7);
}, () => {
flingClose(LIGHTBOX_FLING_VELOCITY_PX_MS * 1.6);
});
}, 420));
}
if (!reduce) {
cycle();
timers.push(window.setInterval(() => {
if (scene.classList.contains(styles['is-demo'])) cycle();
}, LOOP_MS));
}
return () => {
timers.forEach((id) => { window.clearTimeout(id); window.clearInterval(id); });
thumb.removeEventListener('click', onThumbClick);
closeBtn.removeEventListener('click', onCloseClick);
backdrop.removeEventListener('click', onBackdropClick);
document.removeEventListener('keydown', onKeydown);
fullImg.removeEventListener('pointerdown', onPointerDown);
fullImg.removeEventListener('pointermove', onPointerMove);
fullImg.removeEventListener('pointerup', endDrag);
fullImg.removeEventListener('pointercancel', endDrag);
};
}, []);
return (
<div className={`${styles.scene} ${styles['is-demo']}`} ref={sceneRef}>
<ul className={styles.grid}>
<li><button className={styles.thumb} type="button" aria-haspopup="dialog"><span className={styles.thumbImg} /></button></li>
</ul>
<div className={styles.backdrop} />
<div className={styles.lightbox} role="dialog" aria-modal="true" aria-hidden="true" aria-label="사진 던져서 닫기">
<span className={styles.fullImg} />
<p className={styles.dragNote}>아래로 끌어서 닫기</p>
<button className={styles.closeBtn} type="button">닫기</button>
</div>
</div>
);
}06 下に投げるように閉じるライトボックス — 計測 累積面積 39.872% · 動いたフレーム 15/23GODRICH オリジナル · SCSS と React は zip に同梱 · css ライトボックス 拡大アニメーション 9種まとめ
このデモが属する記事
css ライトボックス 拡大アニメーション 9種まとめこの css ライトボックス 9種のうち、1つはクリックしたサムネイルの位置からそのまま拡大し、1つは下向きスワイプの速度を計算して閉じるか戻すかを決め、1つはキーボード移動のたびにフォーカスリングが次の位置へ滑ります。 この記事のデモをすべて見る


