頁面展示刻度滑塊,用戶拖動滑塊時,軌道背景色從灰色漸變至紅色,填充至滑塊當前位置;反向拖動則恢復。
原生 JS 實現需監聽 mousedown/mousemove/mouseup,計算滑塊位置百分比,動態生成 linear-gradient 背景,處理邊界、防抖、觸屏兼容等,代碼量大且易出 Bug。Colorful Sliders 封裝完善,配置簡單:
<input type="range" id="slider" min="0" max="100" value="0" />
<script src="jquery.colorful-sliders.min.js"></script>
<script>
$('#slider').colorfulSlider({
// 自定義顏色停靠點:0% 灰,100% 紅
colors: ['#cccccc', '#ff0000'],
// 或多級漸變
// colors: ['#cccccc', '#ff9900', '#ff0000'],
orientation: 'horizontal',
onChange: function(value) {
console.log('當前值:', value);
}
});
</script>
background: linear-gradient(to right, gray var(--fill%), red 0)。--fill% = (value - min) / (max - min) * 100。requestAnimationFrame 節流渲染,觸屏事件統一 touchmove。background-size 實現動態顯示。range: true 雙滑塊模式,背景填充中間區間。使用成熟插件可將開發時間從數小時縮減至分鐘,專注業務邏輯而非底層交互細節。