前后对比滑块
Before / after slider
两张图叠在一起,拖中间那条线,左边看改之前,右边看改之后
常见大白话搜法:拖中间的线对比改版前后两张图、左右拖动看修图前后的区别、两张图叠在一起拉一条分隔线对比、图片对比滑块
- 适用位置
- 图片
- 气质感觉
- 利落
- 触发方式
- 点击
- 适合网站
- 作品集、个人网站、品牌官网
实现原理与无障碍底线
两张一样大的图叠在一起,后一张用 clip-path 从分隔线的位置往右露出来,分隔线的位置写在一个 CSS 变量上;拖动时分隔线跟着手指走,点一下图上别处或按方向键时平滑地挪过去;分隔线是一个滑块(role="slider"),读屏念得出左右各占多少,左右键、Home、End 都能挪;横着拖不挡住页面上下滑。
适用场景:作品集里的改版前后、修图前后、装修前后、案例页的"用了我们的服务以后":一张图里直接对比,比并排放两张更看得出区别
减少动态(prefers-reduced-motion):点一下、按方向键时分隔线直接到位,不滑;拖动照样跟着手指走
移动端与触屏:手指横着拖分隔线,竖着滑照样滚页面(touch-action: pan-y);分隔线的手柄至少 44px 宽,好按
关键可调参数
| 参数 | 键名 | 默认值 | 建议范围 | 说明 |
|---|---|---|---|---|
| 一开始分隔线在哪 | start | 50% | — | — |
| 点一下时挪过去的时长 | duration | 300ms | — | — |
| 缓动 | easing | cubic-bezier(0.4, 0, 0.2, 1) | — | — |
可直接复制给 AI(Cursor / Claude / v0)的提示词
请在我的项目里给图片加上「前后对比滑块」(Before / after slider)效果:两张一样大的图叠在一起,后一张用 clip-path 从分隔线的位置往右露出来,分隔线的位置写在一个 CSS 变量上;拖动时分隔线跟着手指走,点一下图上别处或按方向键时平滑地挪过去;分隔线是一个滑块(role="slider"),读屏念得出左右各占多少,左右键、Home、End 都能挪;横着拖不挡住页面上下滑。
参数:一开始分隔线在哪 50%,点一下时挪过去的时长 300ms,缓动 cubic-bezier(0.4, 0, 0.2, 1)。
要求:保留原有的内容和布局;系统开启"减少动态"时直接显示最终状态;脚本出错或没有执行时内容仍然可见。
参考:https://donglang.linter.top/effects/before-after.md(原理、参数和参考代码)原生无依赖参考代码
CSS
/* 前后对比滑块(Before / after slider)的样式,配合 before-after.js。外框 class="ba",里面先放改之前的 .ba-before、再放改之后的 .ba-after(两张一样大)。
后一张铺满外框、盖在上面,用 clip-path 从分隔线(--ba-pos,默认 50%)往右露出来;分隔线 .ba-handle 由脚本加进来,跟着 --ba-pos 走。
点一下、按键时分隔线和露出的部分用过渡挪过去(--ba-duration、--ba-easing,由脚本的选项写到外框上);拖动时外框有 ba-dragging,不过渡、跟手。
--ba-line:分隔线的颜色(默认白色)。没有脚本时两张图各露一半,内容照样看得见。
开启"减少动态"时:点一下、按键时直接到位,不滑。 */
:where(.ba) {
--ba-pos: 50%;
--ba-duration: 300ms;
--ba-easing: cubic-bezier(0.4, 0, 0.2, 1);
--ba-line: #fff;
}
.ba {
position: relative;
overflow: hidden;
touch-action: pan-y;
user-select: none;
}
.ba > .ba-before,
.ba > .ba-after {
display: block;
width: 100%;
}
.ba > .ba-after {
position: absolute;
inset: 0;
height: 100%;
object-fit: cover;
clip-path: inset(0 0 0 var(--ba-pos));
}
.ba.ba-js { cursor: ew-resize; }
.ba-handle {
position: absolute;
top: 0;
bottom: 0;
left: var(--ba-pos);
width: 44px;
margin-left: -22px;
outline: none;
}
/* 中间一条细线,正中一个圆把手 */
.ba-handle::before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 2px;
margin-left: -1px;
background: var(--ba-line);
box-shadow: 0 0 4px rgb(0 0 0 / 0.35);
}
.ba-handle::after {
content: "";
position: absolute;
left: 50%;
top: 50%;
width: 32px;
height: 32px;
margin: -16px 0 0 -16px;
border: 2px solid var(--ba-line);
border-radius: 50%;
box-sizing: border-box;
background: rgb(0 0 0 / 0.25);
box-shadow: 0 0 4px rgb(0 0 0 / 0.35);
}
.ba-handle:focus-visible::after { outline: 3px solid var(--ba-line); outline-offset: 2px; }
.ba.ba-js > .ba-after { transition: clip-path var(--ba-duration) var(--ba-easing); }
.ba.ba-js > .ba-handle { transition: left var(--ba-duration) var(--ba-easing); }
.ba.ba-dragging > .ba-after,
.ba.ba-dragging > .ba-handle { transition: none; }
@media (prefers-reduced-motion: reduce) {
.ba.ba-js:not(.ba-force) > .ba-after,
.ba.ba-js:not(.ba-force) > .ba-handle { transition: none; }
}JavaScript
// 前后对比滑块(Before / after slider)· 原生 JS,不依赖任何库。
// 同类效果见 Motion Lexicon 的 before-after-slider(MIT);本站按通用做法自己实现,没有复制代码。
// 用法:外框 <div class="ba">,里面两张一样大的图:先放改之前的(.ba-before),再放改之后的(.ba-after),调 beforeAfter(外框),配合 before-after.css。
// 后一张用 clip-path 从分隔线的位置往右露出来(左边看到改之前,右边看到改之后);分隔线的位置写在外框的 --ba-pos 上(百分比)。
// 脚本在外框里加一条分隔线(.ba-handle,role="slider",Tab 能选中),没有脚本时就是两张图各露一半,内容照样看得见。
// - 拖动:在图上任何地方按住左右拖,分隔线跟着指针走(不过渡);只按一下不拖,分隔线平滑地挪到按下的地方(duration、easing 的过渡)。
// 外框写了 touch-action: pan-y:手指横着拖是拖分隔线,竖着滑照样滚页面。同一时间只认一根手指(第二根不抢)。
// - 键盘(分隔线选中时):左右方向键每次挪 5%(按住 Shift 挪 10%),Home、End 到最左、最右,挪的时候同样平滑。
// - 读屏:分隔线是滑块,aria-valuenow 是分隔线在哪(0–100),aria-valuetext 念"改之前占 40%,改之后占 60%";
// 句子用 messages 选项换(value 函数,参数是分隔线在哪),无障碍名用 label 选项换(默认"拖动对比改之前和改之后")。
// - 位置变了(拖动中每次变、点一下或按键后各一次)在外框上发 beforeafterchange 事件(detail.value),发的时候样式和属性已经是新的了。
// 选项:start(一开始分隔线在哪,%)、duration(点一下、按键时挪过去的时长,ms)、easing(缓动);
// 开启"减少动态"时:点一下、按键时直接到位,不滑;拖动照样跟着手指走。ignoreReducedMotion 只给演示用。
// 支持的布局:外框里两张图叠在同一个地方(before-after.css 让外框 position: relative、后一张 absolute 铺满);外框宽度是 0 时不改位置、不发事件。
// 返回 { set(value, { animate }), value(), destroy() }:set 用代码挪(animate 默认 true,false 直接到位);
// destroy 摘掉监听、拿掉分隔线和加上的样式,回到没有脚本时的样子,之后 set 什么都不做;对同一个外框重复调用,先 destroy 旧的。
const prevs = new WeakMap();
export function beforeAfter(root, {
start = 50,
duration = 300,
easing = 'cubic-bezier(0.4, 0, 0.2, 1)',
ignoreReducedMotion = false,
label = '拖动对比改之前和改之后',
messages = {},
} = {}) {
prevs.get(root)?.destroy();
const text = messages.value ?? ((v) => `改之前占 ${v}%,改之后占 ${100 - v}%`);
const clamp = (v) => Math.min(100, Math.max(0, Number(v) || 0));
const style = root.getAttribute('style');
const handle = document.createElement('div');
handle.className = 'ba-handle';
handle.setAttribute('role', 'slider');
handle.setAttribute('aria-label', label);
handle.setAttribute('aria-valuemin', '0');
handle.setAttribute('aria-valuemax', '100');
handle.setAttribute('aria-orientation', 'horizontal');
handle.tabIndex = 0;
root.append(handle);
root.style.setProperty('--ba-duration', `${duration}ms`);
root.style.setProperty('--ba-easing', easing);
if (ignoreReducedMotion) root.classList.add('ba-force');
root.classList.add('ba-js');
let value = clamp(start);
let dead = false;
// 拖动中:外框加 ba-dragging(CSS 关掉过渡,分隔线跟手)
let active = null;
// animate 为 false:先关过渡(ba-dragging)、写位置、强制回流,拖动中保留 ba-dragging(下一次移动接着跟手),不在拖时马上拿掉
const write = (v, animate) => {
if (!animate) root.classList.add('ba-dragging');
else if (!active) root.classList.remove('ba-dragging');
value = Math.round(clamp(v) * 100) / 100;
root.style.setProperty('--ba-pos', `${value}%`);
const shown = Math.round(value);
handle.setAttribute('aria-valuenow', String(shown));
handle.setAttribute('aria-valuetext', text(shown));
if (!animate && !active?.moved) {
void root.offsetWidth;
root.classList.remove('ba-dragging');
}
};
const set = (v, { animate = true } = {}) => {
if (dead || !(root.clientWidth > 0)) return false;
const before = value;
write(v, animate);
if (value !== before) root.dispatchEvent(new CustomEvent('beforeafterchange', { detail: { value } }));
return true;
};
const at = (clientX) => {
const r = root.getBoundingClientRect();
return r.width > 0 ? ((clientX - r.left) / r.width) * 100 : value;
};
const onDown = (e) => {
if (active || (e.pointerType === 'mouse' && e.button !== 0)) return;
// 按在分隔线上就直接跟手;按在图上别处先平滑地挪过去,拖起来再跟手
const onHandle = handle.contains(e.target);
active = { id: e.pointerId, x: e.clientX, moved: onHandle };
root.setPointerCapture?.(e.pointerId);
if (onHandle) root.classList.add('ba-dragging');
else set(at(e.clientX));
handle.focus({ preventScroll: true });
e.preventDefault();
};
const onMove = (e) => {
if (!active || e.pointerId !== active.id) return;
if (!active.moved && Math.abs(e.clientX - active.x) < 3) return;
active.moved = true;
set(at(e.clientX), { animate: false });
};
const onUp = (e) => {
if (!active || e.pointerId !== active.id) return;
active = null;
root.classList.remove('ba-dragging');
};
const onKey = (e) => {
const step = e.shiftKey ? 10 : 5;
const next = { ArrowLeft: value - step, ArrowDown: value - step, ArrowRight: value + step, ArrowUp: value + step, Home: 0, End: 100 }[e.key];
if (next === undefined) return;
e.preventDefault();
set(next);
};
const listeners = [
[root, 'pointerdown', onDown],
[root, 'pointermove', onMove],
[root, 'pointerup', onUp],
[root, 'pointercancel', onUp],
[root, 'lostpointercapture', onUp],
[handle, 'keydown', onKey],
];
for (const [target, type, fn] of listeners) target.addEventListener(type, fn);
// 直接放到起点(不播过渡):装上以后马上 set() 也从起点滑过去
write(value, false);
const ctl = {
set,
value: () => value,
destroy() {
if (dead) return;
dead = true;
for (const [target, type, fn] of listeners) target.removeEventListener(type, fn);
handle.remove();
root.classList.remove('ba-js', 'ba-force', 'ba-dragging');
// 原来没有 style 属性就拿掉它。先读一次属性:Chromium 里刚改过 style 的元素直接 removeAttribute,之后会补回一个空的 style=""
if (style === null) { void root.getAttribute('style'); root.removeAttribute('style'); }
else root.setAttribute('style', style);
active = null;
if (prevs.get(root) === ctl) prevs.delete(root);
},
};
prevs.set(root, ctl);
return ctl;
}HTML
<!-- 前后对比滑块:外框 class="ba",先放改之前的图,再放改之后的图(两张一样大);分隔线由脚本加进来 -->
<div class="ba" id="redesign">
<img class="ba-before" src="改版前.jpg" alt="改版前的首页">
<img class="ba-after" src="改版后.jpg" alt="改版后的首页">
</div>
<script type="module">
import { beforeAfter } from './before-after.js';
beforeAfter(document.getElementById('redesign'), { start: 50, duration: 300 });
</script>