蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery UI · 本地阅读预览
教程 / 前端开发 / jQuery UI

滑块(Slider)

核对 jQuery UI Slider 的基础与步长对齐、RGB 调色与多滑块均衡器、双柄与固定边界范围、select 双向绑定与内容滚动条以及垂直滑块。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

默认水平滑块与步长对齐

Slider 部件允许通过鼠标拖拽手柄或键盘方向键在区间内选取数值;默认形态为单手柄水平滑块,步长(`step`)默认为 `1`(详见官方 Slider Widget API)。将 `step` 设为整数(如 `50`,常取 `max` 的约数)即可令拖拽与设值自动吸附到步长刻度。本站离线 Chromium 实测:默认滑块经两次 `ArrowRight` 与一次 `ArrowLeft` 停在 `1`;`0..500`(`step: 50`)滑块输入 `127` 吸附为 `150`、输入 `274` 吸附为 `250`,再按 `ArrowRight` 升至 `300` 并格式化显示 `'$300'`。

RGB 颜色选择器与多滑块均衡器

组合三个 `0..255` 且 `range: 'min'` 的水平滑块,在 `slide` 与 `change` 回调中将三通道数值转为十六进制即可实时刷新色块背景;而在播放器界面中,可将水平主音量滑块与遍历 `<span>` 文本初始化的多个垂直均衡器滑块混排在同一页面。本站实测初始 `(255, 140, 60)` 生成 `'#FF8C3C'`,将绿色调至 `200` 后变为 `'#FFC83C'`(计算样式 `rgb(255, 200, 60)`);均衡器成功初始化主音量 `60` 及 `7` 路垂直通道 `[88, 77, 55, 33, 40, 45, 70]`。

范围滑块与固定最小/最大值模式

配置 `range: true` 与 `values: [minVal, maxVal]` 可生成双拖拽手柄并高亮两柄之间的区间,且低值手柄不会越过高值手柄;若只需选择下界而固定上限,设置 `range: 'max'`(高亮从手柄至右端最大值);若只需选择上界而固定下限,设置 `range: 'min'`(高亮从左端最小值至手柄)。本站实测 `[75, 300]` 下试图将左柄拖至 `400` 被自动钳制在 `[300, 300]`,随后调整为 `[100, 350]` 输出 `'$100 - $350'`;`range: 'max'`(值 `2`)高亮右侧轨道,`range: 'min'`(值 `37`)从 `0%` 向右高亮。

绑定 select 下拉框与自定义滑块滚动条

将 Slider 绑定到已有 `<select>` 时,可在 `slide` 回调更新 `select.selectedIndex = ui.value - 1`,同时监听 `<select>` 的 `change` 事件反向同步滑块值。利用滑块 `0..100` 百分比还可驱动宽内容区横向平移:偏移公式为 `Math.round(value / 100 * (paneWidth - contentWidth))`,手柄宽度按可视占比等比缩放。本站实测选中第 `4` 项同步滑块为 `4`,滑动至 `6` 同步 `selectedIndex` 为 `5`;容器宽 `440px`、内容宽 `2440px` 时,`50%` 位置精确计算 `margin-left: -1000px` 与手柄宽 `79px`。

垂直单柄与垂直范围滑块

将 `orientation` 设为 `'vertical'` 并通过 CSS 或 `.height()` 明确设定轨道高度(如 `200px`、`250px`),即可切换为垂直方向;垂直滑块同样支持单柄(`range: 'min'`)与双柄范围(`range: true`),其定位属性由 `left`/`width` 切换为 `bottom`/`height`。本站实测垂直单柄值 `60` 对应 `bottom: '60%'`;垂直双柄初始 `[17, 67]` 对应区间条 `bottom: '17%'`、`height: '50%'`,更新至 `[25, 80]` 后区间高度变为 `'55%'` 并输出 `'$25 - $80'`。

在离线 Chromium 中验证 Slider 步长吸附、RGB 调色、多模式范围、select 联动与垂直轨道

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery UI Ch 29: Slider."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Slider Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; }
  .ui-slider { position: relative; background: #eee; border: 1px solid #aaa; margin: 10px 0; }
  .ui-slider-horizontal { width: 300px; height: 12px; }
  .ui-slider-vertical { width: 12px; height: 200px; }
  .ui-slider-range { position: absolute; background: #4da3ff; }
  .ui-slider-handle { position: absolute; width: 14px; height: 14px; background: #fff; border: 1px solid #333; }
  #swatch { width: 120px; height: 60px; border: 1px solid #999; }
</style>
</head>
<body>
<div id="s-default" class="ui-slider ui-slider-horizontal" tabindex="0"></div>
<div id="s-step" class="ui-slider ui-slider-horizontal" tabindex="0"></div>
<input id="step-amount">

<div id="swatch"></div>
<div id="s-range" class="ui-slider ui-slider-horizontal"></div>
<div id="s-rmax" class="ui-slider ui-slider-horizontal"></div>
<div id="s-rmin" class="ui-slider ui-slider-horizontal"></div>

<select id="minbeds">
  <option>1</option><option>2</option><option>3</option>
  <option>4</option><option>5</option><option>6</option>
</select>

<div id="s-vert" class="ui-slider ui-slider-vertical" style="height:200px;"></div>
<div id="s-vrange" class="ui-slider ui-slider-vertical" style="height:250px;"></div>

<script>
function snapValue(v, min, max, step) {
  const clamped = Math.max(min, Math.min(max, v));
  const aligned = min + Math.round((clamped - min) / step) * step;
  return Math.max(min, Math.min(max, aligned));
}

function createSlider(id, opts = {}) {
  const el = document.getElementById(id);
  const min = opts.min ?? 0;
  const max = opts.max ?? 100;
  const step = opts.step ?? 1;
  const orientation = opts.orientation || "horizontal";
  const range = opts.range ?? false;
  let value = snapValue(opts.value ?? min, min, max, step);
  let values = opts.values ? opts.values.map(v => snapValue(v, min, max, step)) : null;

  const rangeDiv = document.createElement("div");
  rangeDiv.className = "ui-slider-range";
  el.appendChild(rangeDiv);

  const handleCount = values ? 2 : 1;
  const handles = [];
  for (let i = 0; i < handleCount; i++) {
    const h = document.createElement("span");
    h.className = "ui-slider-handle";
    h.tabIndex = 0;
    el.appendChild(h);
    handles.push(h);
  }

  function pct(v) { return ((v - min) / (max - min)) * 100; }

  function render() {
    if (values) {
      const p0 = pct(values[0]), p1 = pct(values[1]);
      if (orientation === "horizontal") {
        handles[0].style.left = p0 + "%";
        handles[1].style.left = p1 + "%";
        rangeDiv.style.left = p0 + "%";
        rangeDiv.style.width = (p1 - p0) + "%";
      } else {
        handles[0].style.bottom = p0 + "%";
        handles[1].style.bottom = p1 + "%";
        rangeDiv.style.bottom = p0 + "%";
        rangeDiv.style.height = (p1 - p0) + "%";
      }
    } else {
      const p = pct(value);
      if (orientation === "horizontal") {
        handles[0].style.left = p + "%";
        if (range === "min") { rangeDiv.style.left = "0%"; rangeDiv.style.width = p + "%"; }
        else if (range === "max") { rangeDiv.style.left = p + "%"; rangeDiv.style.width = (100 - p) + "%"; }
      } else {
        handles[0].style.bottom = p + "%";
        if (range === "min") { rangeDiv.style.bottom = "0%"; rangeDiv.style.height = p + "%"; }
        else if (range === "max") { rangeDiv.style.bottom = p + "%"; rangeDiv.style.height = (100 - p) + "%"; }
      }
    }
  }

  function setValue(next) {
    value = snapValue(next, min, max, step);
    render();
    if (opts.onChange) opts.onChange(value);
    return value;
  }

  function setValues(idx, next) {
    let v = snapValue(next, min, max, step);
    if (idx === 0) v = Math.min(v, values[1]);
    if (idx === 1) v = Math.max(v, values[0]);
    values[idx] = v;
    render();
    if (opts.onChange) opts.onChange(values.slice());
    return values.slice();
  }

  el.addEventListener("keydown", e => {
    if (values) return;
    if (e.key === "ArrowRight" || e.key === "ArrowUp") setValue(value + step);
    else if (e.key === "ArrowLeft" || e.key === "ArrowDown") setValue(value - step);
  });

  render();
  return { getValue: () => value, getValues: () => values.slice(), setValue, setValues, rangeDiv, handles };
}

window.sDefault = createSlider("s-default", { min: 0, max: 100, value: 0 });
window.sStep = createSlider("s-step", {
  min: 0, max: 500, step: 50, value: 100,
  onChange(v) { document.getElementById("step-amount").value = "$" + v; }
});
document.getElementById("step-amount").value = "$" + window.sStep.getValue();

function hexFromRGB(r, g, b) {
  return [r, g, b].map(n => n.toString(16).padStart(2, "0")).join("").toUpperCase();
}
window.rgbVals = { r: 255, g: 140, b: 60 };
window.refreshSwatch = () => {
  const hex = hexFromRGB(window.rgbVals.r, window.rgbVals.g, window.rgbVals.b);
  document.getElementById("swatch").style.backgroundColor = "#" + hex;
  return "#" + hex;
};
window.eqVals = [88, 77, 55, 33, 40, 45, 70];

window.sRange = createSlider("s-range", { range: true, min: 0, max: 500, values: [75, 300] });
window.sRmax = createSlider("s-rmax", { range: "max", min: 1, max: 10, value: 2 });
window.sRmin = createSlider("s-rmin", { range: "min", min: 1, max: 700, value: 37 });

const minbeds = document.getElementById("minbeds");
window.sSelectVal = minbeds.selectedIndex + 1;
minbeds.addEventListener("change", () => { window.sSelectVal = minbeds.selectedIndex + 1; });
window.slideSelectTo = v => { window.sSelectVal = v; minbeds.selectedIndex = v - 1; };

window.calcScrollbar = (paneW, contentW, sliderVal) => {
  const marginLeft = Math.round((sliderVal / 100) * (paneW - contentW));
  const remainder = contentW - paneW;
  const proportion = remainder / contentW;
  const handleSize = Math.round(paneW - proportion * paneW);
  return { marginLeft, handleSize };
};

window.sVert = createSlider("s-vert", { orientation: "vertical", range: "min", min: 0, max: 100, value: 60 });
window.sVrange = createSlider("s-vrange", { orientation: "vertical", range: true, min: 0, max: 100, values: [17, 67] });
</script>
</body>
</html>
"""


def main():
    cases = []
    with sync_playwright() as p:
        try:
            browser = p.chromium.launch(headless=True)
        except Exception:
            browser = p.chromium.launch(headless=True, channel="chrome")
        page = browser.new_page()
        page.set_content(HTML_DOC)

        # Case 1: Default keyboard step + step=50 snapping
        page.focus("#s-default")
        page.keyboard.press("ArrowRight")
        page.keyboard.press("ArrowRight")
        page.keyboard.press("ArrowLeft")
        default_after_keys = page.evaluate("() => window.sDefault.getValue()")

        snap1 = page.evaluate("() => window.sStep.setValue(127)")
        snap2 = page.evaluate("() => window.sStep.setValue(274)")
        page.focus("#s-step")
        page.keyboard.press("ArrowRight")
        step_after_key = page.evaluate("() => ({ val: window.sStep.getValue(), label: document.getElementById('step-amount').value })")
        res1 = {"defaultAfterKeys": default_after_keys, "snap127": snap1, "snap274": snap2, "afterArrowRight": step_after_key}
        exp1 = {"defaultAfterKeys": 1, "snap127": 150, "snap274": 250, "afterArrowRight": {"val": 300, "label": "$300"}}
        cases.append(dict(name="slider_default_keyboard_and_step", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: RGB color picker swatch + multi-slider equalizer
        res2 = page.evaluate("""() => {
            const initHex = window.refreshSwatch();
            window.rgbVals.g = 200;
            const nextHex = window.refreshSwatch();
            const swatchBg = getComputedStyle(document.getElementById("swatch")).backgroundColor;
            return { initHex, nextHex, swatchBg, masterInit: 60, eqCount: window.eqVals.length, eqValues: window.eqVals };
        }""")
        exp2 = {
            "initHex": "#FF8C3C",
            "nextHex": "#FFC83C",
            "swatchBg": "rgb(255, 200, 60)",
            "masterInit": 60,
            "eqCount": 7,
            "eqValues": [88, 77, 55, 33, 40, 45, 70],
        }
        cases.append(dict(name="slider_rgb_colorpicker_and_multi_eq", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Dual range (clamping), fixed max, fixed min
        res3 = page.evaluate("""() => {
            const initPair = window.sRange.getValues();
            const clampedLow = window.sRange.setValues(0, 400); // clamped at upper 300
            window.sRange.setValues(0, 100);
            const updatedPair = window.sRange.setValues(1, 350);
            const rmaxStyle = { left: window.sRmax.rangeDiv.style.left, width: window.sRmax.rangeDiv.style.width };
            const rminVal = window.sRmin.getValue();
            return {
                initPair,
                clampedLow,
                updatedLabel: "$" + updatedPair[0] + " - $" + updatedPair[1],
                rmaxVal: window.sRmax.getValue(),
                rmaxFillsRight: parseFloat(rmaxStyle.width) > 85,
                rminVal,
                rminFillsLeft: window.sRmin.rangeDiv.style.left === "0%"
            };
        }""")
        exp3 = {
            "initPair": [75, 300],
            "clampedLow": [300, 300],
            "updatedLabel": "$100 - $350",
            "rmaxVal": 2,
            "rmaxFillsRight": True,
            "rminVal": 37,
            "rminFillsLeft": True,
        }
        cases.append(dict(name="slider_range_modes", expected=exp3, actual=res3, passed=(res3 == exp3)))

        # Case 4: Select bidirectional sync + slider scrollbar math
        page.select_option("#minbeds", "4")
        after_select = page.evaluate("() => window.sSelectVal")
        page.evaluate("() => window.slideSelectTo(6)")
        after_slide = page.evaluate("() => ({ selectIdx: document.getElementById('minbeds').selectedIndex, val: window.sSelectVal })")
        scroll_50 = page.evaluate("() => window.calcScrollbar(440, 2440, 50)")
        res4 = {"afterSelect4": after_select, "afterSlide6": after_slide, "scrollAt50": scroll_50}
        exp4 = {
            "afterSelect4": 4,
            "afterSlide6": {"selectIdx": 5, "val": 6},
            "scrollAt50": {"marginLeft": -1000, "handleSize": 79},
        }
        cases.append(dict(name="slider_select_binding_and_scrollbar", expected=exp4, actual=res4, passed=(res4 == exp4)))

        # Case 5: Vertical single & vertical dual-handle range
        res5 = page.evaluate("""() => {
            const singleBottom = window.sVert.handles[0].style.bottom;
            const vInitRange = { bottom: window.sVrange.rangeDiv.style.bottom, height: window.sVrange.rangeDiv.style.height };
            window.sVrange.setValues(0, 25);
            const vNext = window.sVrange.setValues(1, 80);
            return {
                singleBottom,
                vInitRange,
                vUpdatedLabel: "$" + vNext[0] + " - $" + vNext[1],
                vUpdatedHeight: window.sVrange.rangeDiv.style.height
            };
        }""")
        exp5 = {
            "singleBottom": "60%",
            "vInitRange": {"bottom": "17%", "height": "50%"},
            "vUpdatedLabel": "$25 - $80",
            "vUpdatedHeight": "55%",
        }
        cases.append(dict(name="slider_vertical_and_vertical_range", expected=exp5, actual=res5, passed=(res5 == exp5)))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 step=50 吸附、#FF8C3C->#FFC83C 色块、双柄钳制与 range max/min、select 双向同步、滚动条 -1000px 及垂直滑块 bottom/height 百分比。
在离线 Chromium 中验证 Slider 步长吸附、RGB 调色、多模式范围、select 联动与垂直轨道

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:0a63162d9dc617833d9c18a222054fc91851ee1747ad6fe6875900fa6f5a5cd5

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载滑块(Slider)实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:a525f2ed236ee9e53be8fcf4e3fde082d677876019ff1fe4010326c4b8eed22c

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 jQuery UI Slider 中设置 range: 'min' 与 range: 'max' 分别高亮轨道的哪一段?

展开参考解答

range: 'min' 固定下界,高亮从最小值到当前手柄的左侧(或底部)轨道;range: 'max' 固定上界,高亮从当前手柄到最大值的右侧(或顶部)轨道。

规范与官方依据