現代瀏覽器(IE10+、Edge、Chrome、Firefox、Safari)均完美支持。僅需兼容 IE9 及以下時才需自定義實現。
<div id="slider" class="slider" data-min="0" data-max="100" data-value="50">
<div class="slider-track"></div>
<div class="slider-thumb"></div>
</div>
<output id="slider-value">50</output>
<style>
.slider {
position: relative;
width: 300px;
height: 8px;
background: #ddd;
border-radius: 4px;
cursor: pointer;
}
.slider-track {
position: absolute;
left: 0; top: 0; bottom: 0;
background: #007bff;
border-radius: 4px;
transition: width 0.1s;
}
.slider-thumb {
position: absolute;
top: 50%;
width: 20px; height: 20px;
margin-top: -10px;
background: #fff;
border: 2px solid #007bff;
border-radius: 50%;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
transform: translateX(-50%);
pointer-events: none;
}
</style>
$.fn.slider = function(options) {
const defaults = {min: 0, max: 100, step: 1, value: 0};
const opts = $.extend({}, defaults, options);
return this.each(function() {
const $slider = $(this);
const $track = $slider.find('.slider-track');
const $thumb = $slider.find('.slider-thumb');
const $output = $(`#${$slider.data('output')}`);
// 初始化屬性
const min = Number($slider.data('min')) || opts.min;
const max = Number($slider.data('max')) || opts.max;
let value = Number($slider.data('value')) || opts.value;
const updateUI = (val) => {
const percent = (val - min) / (max - min) * 100;
$track.css('width', `${percent}%`);
$thumb.css('left', `${percent}%`);
$output.text(val);
$slider.trigger('slide', [val]);
};
// 滑鼠/觸摸事件
const moveHandler = (e) => {
e.preventDefault();
const rect = $slider[0].getBoundingClientRect();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
let percent = (clientX - rect.left) / rect.width;
percent = Math.max(0, Math.min(1, percent));
const val = Math.round(min + percent * (max - min));
const stepped = Math.round(val / opts.step) * opts.step;
value = Math.max(min, Math.min(max, stepped));
updateUI(value);
};
$slider.on('mousedown touchstart', (e) => {
moveHandler(e);
$(document).on('mousemove.slider touchmove.slider', moveHandler);
$(document).one('mouseup.slider touchend.slider', () => {
$(document).off('.slider');
$slider.trigger('change', [value]);
});
});
// 鍵盤支持
$slider.on('keydown', (e) => {
if ([37, 39].includes(e.which)) { // Left/Right
e.preventDefault();
value += (e.which === 39 ? 1 : -1) * opts.step;
value = Math.max(min, Math.min(max, value));
updateUI(value);
}
});
updateUI(value);
// 公開方法
$slider.data('slider-api', {
getValue: () => value,
setValue: (v) => updateUI(Math.max(min, Math.min(max, v))),
disable: () => $slider.addClass('disabled').off('.slider'),
enable: () => $slider.removeClass('disabled')
});
});
};
// 使用
$('#slider').slider({min: 0, max: 100, step: 5, value: 30});
$('#slider').on('change', (e, val) => console.log('Final:', val));
role="slider"aria-valuemin、aria-valuemax、aria-valuenow、aria-orientation="horizontal":focus-visible 樣式<input type="range">,CSS 美化即可window/document