萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現跨瀏覽器 HTML5 滑塊組件:從原理到生產級封裝

原生 input[type=range] 兼容性現狀

現代瀏覽器(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>

jQuery 交互邏輯封裝

$.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));

無障礙(a11y)增強

  • 角色:role="slider"
  • 屬性:aria-valuemin、aria-valuemax、aria-valuenow、aria-orientation="horizontal"
  • 鍵盤操作:←/→ 鍵調整,Home/End 跳至極值
  • 焦點可見::focus-visible 樣式

生產級建議

  • 優先使用原生 <input type="range">,CSS 美化即可
  • 複雜需求(雙滑塊、標記、縮放)考慮成熟庫:noUiSlider、rangeslider.js
  • TypeScript 類型定義、單元測試、Storybook 文檔
  • SSR 兼容:避免構建期訪問 window/document
copyright © 萬盛學電腦網 all rights reserved