一个双滑块范围选择器组件库
This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greasyfork.org/scripts/593075/1913652/RangeSlider.js
RangeSlider 是一个轻量级的双滑块范围选择器 JavaScript 组件库,支持区间选择、平滑动画过渡与键盘辅助操作。
// 准备 DOM 容器
const container = document.getElementById('slider-container');
// 初始化组件
const slider = new RangeSlider(container, {
min: 0,
max: 100,
from: 20,
to: 80,
onChange: (res) => {
console.log('当前选中范围:', res.from, res.to);
}
});
初始化时可传入以下参数配置对象:
| 参数名 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| min | number |
0 |
最小值 |
| max | number |
100 |
最大值 |
| step | number |
1 |
步长 |
| from | number |
min |
左滑块初始值 |
| to | number |
max |
右滑块初始值 |
| onChange | function |
() => {} |
数值变更时的回调函数 |
onChange 回调会接收一个包含最新数值的对象:
{
from: 20, // 当前选中的起始值(自动取较小值)
to: 80 // 当前选中的结束值(自动取较大值)
}
初始化后,可以通过实例调用以下方法更新状态:
setValues(values, animate)设置滑块的数值。
values (object): 包含 { from, to } 的对象,字段可选。animate (boolean): 是否开启过渡动画,默认为 false。
示例:
// 无动画直接更新
slider.setValues({ from: 10, to: 90 });
// 带动画过度效果更新
slider.setValues({ from: 30, to: 70 }, true);
step 调整min / max 极限值组件样式通过 CSS 变量暴露,可在外部直接重写变量定义修改外观:
.cs-slider-container {
--cs-track-bg: #e4e7ed; /* 轨道背景色 */
--cs-progress-bg: #409eff; /* 选中区间进度条颜色 */
--cs-thumb-bg: #fff; /* 滑块背景色 */
--cs-thumb-border: #409eff; /* 滑块边框颜色 */
--cs-thumb-shadow: rgba(0, 0, 0, 0.2); /* 滑块阴影 */
--cs-thumb-focus-shadow: rgba(64, 158, 255, 0.3); /* 滑块聚焦高亮阴影 */
}