中文
Click & feedback · Vanilla JS + CSS

Before / after slider

前后对比滑块

Stack two images and drag the divider to compare before on the left with after on the right.

Also searched as: 拖中间的线对比改版前后两张图, 左右拖动看修图前后的区别, 两张图叠在一起拉一条分隔线对比, 图片对比滑块

AI Markdown (.md)
Placement
Image
Mood
Crisp
Trigger
点击
Site types
作品集, 个人网站, 品牌官网

How it works & accessibility

The after image is clipped with clip-path from a --ba-pos custom property; dragging follows the pointer with no transition while a click or arrow key glides the divider there, the divider is a role=slider with aria-valuetext and arrow, Home and End keys, touch-action: pan-y keeps vertical scrolling, and with reduced motion clicks and keys jump instead of gliding.

Best for: Image (点击).

Reduced motion: 点一下、按方向键时分隔线直接到位,不滑;拖动照样跟着手指走

Mobile & touch: 手指横着拖分隔线,竖着滑照样滚页面(touch-action: pan-y);分隔线的手柄至少 44px 宽,好按

Key parameters

ParameterKeyDefaultRangeNotes
一开始分隔线在哪start50%——
点一下时挪过去的时长duration300ms——
缓动easingcubic-bezier(0.4, 0, 0.2, 1)——

Ready-to-paste AI prompt

Add “Before / after slider” to the image in my project: The after image is clipped with clip-path from a --ba-pos custom property; dragging follows the pointer with no transition while a click or arrow key glides the divider there, the divider is a role=slider with aria-valuetext and arrow, Home and End keys, touch-action: pan-y keeps vertical scrolling, and with reduced motion clicks and keys jump instead of gliding.
Parameters: start: 50%, duration: 300ms, easing: cubic-bezier(0.4, 0, 0.2, 1).
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/before-after.md (canonical specification and reference code).

Dependency-free reference code

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>

More in Click & feedback

Browse all 86 effects →

Shown once per release · Always available in changelog