技能概述
Before & After Slider 生成一個交互式對比組件,用戶可拖拽中間的滑塊來比較「修改前」和「修改後」的視覺效果。基於純 CSS clip-path 和少量 JS 拖拽邏輯,單一 HTML 文件,零外部依賴。適用於設計改版展示、照片修圖對比、產品迭代效果演示。
觸發關鍵字
- before and after slider、前後對比、對比滑塊、comparison slider
- before/after、design comparison、改版纳入對比
什麼時候用
- 展示設計改版前後效果
- 照片修圖/濾鏡效果對比
- 產品升級前後差異展示
- A/B 測試結果視覺化
使用方法
實際場景
場景一:品牌視覺升級展示
品牌重設計後,需要向客戶展示新舊 logo、配色、字體的對比。拖拽滑塊讓客戶直觀感受到升級效果,比靜態並排展示更具說服力。
場景二:照片修圖作品展示
攝影師展示原片和精修版本的對比。滑塊交互讓觀眾自己探索細節差異,增強參與感。
核心實現
<div class="comparison-slider">
<div class="before-image" style="background: url('before.jpg')"></div>
<div class="after-image" style="background: url('after.jpg'); clip-path: inset(0 50% 0 0)">
</div>
<div class="slider-handle" style="left: 50%"></div>
</div>
<style>
.comparison-slider {
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
overflow: hidden;
border-radius: 12px;
}
.before-image, .after-image {
position: absolute;
inset: 0;
background-size: cover;
background-position: center;
}
.slider-handle {
position: absolute;
top: 0; bottom: 0;
width: 4px;
background: white;
cursor: ew-resize;
}
</style>
<script>
// 拖拽邏輯:監聽 mousemove/touchmove 更新 clip-path 和 handle 位置
const slider = document.querySelector('.comparison-slider');
let isDragging = false;
slider.addEventListener('mousedown', () => isDragging = true);
slider.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const rect = slider.getBoundingClientRect();
const x = ((e.clientX - rect.left) / rect.width) * 100;
const afterImg = slider.querySelector('.after-image');
const handle = slider.querySelector('.slider-handle');
afterImg.style.clipPath = `inset(0 ${100 - x}% 0 0)`;
handle.style.left = x + '%';
});
document.addEventListener('mouseup', () => isDragging = false);
</script>
自檢清單
- 滑塊拖拽流暢,無卡頓
- 支持觸控設備(touchmove 事件)
- 兩邊圖片尺寸一致、位置對齊
- 標籤清晰(BEFORE / AFTER)
- 響應式佈局適配不同螢幕
使用場景示例
場景一:品牌視覺升級展示
品牌重設計後,向客戶展示新舊 logo、配色、字體的對比。拖拽滑塊讓客戶直觀感受升級效果,比靜態並排更具說服力。
場景二:照片修圖作品展示
攝影師展示原片和精修版本的對比。滑塊交互讓觀眾自己探索細節差異,增強參與感。
場景三:App UI 改版對比
展示 App 改版前後的界面對比,突出新版本在信息層級、可讀性和美觀度上的提升。適合向產品團隊或客戶匯報設計成果。
參考資源
- CSS clip-path 指南 (MDN)
- TwentyTwenty 對比插件 — 經典 jQuery 方案
- CSS Tricks: Before/After Slider — 純 CSS 實現思路