Bootstrap 5 中,选择区间(Range Input)是一个用于选择数值区间的表单元素,通常表现为一个滑块。用户通过滑动滑块来选择一个数值,通常用于设定范围或调整某些设置(如音量、亮度等)。

1. 基本选择区间

以下是一个简单的选择区间示例:

<div class="mb-3">
  <label for="customRange1" class="form-label">Example Range</label>
  <input type="range" class="form-range" id="customRange1">
</div>

  • type="range":定义了一个范围输入。
  • class="form-range":Bootstrap 5 提供的样式类,用于美化滑块。
  • id="customRange1":标识该输入框的唯一标识符。

2. 设置最小值、最大值和步长

你可以使用 minmaxstep 属性来设置范围的最小值、最大值和步长。

<div class="mb-3">
  <label for="customRange2" class="form-label">Range with min, max, and step</label>
  <input type="range" class="form-range" id="customRange2" min="0" max="100" step="10">
</div>

  • min="0":设置范围的最小值为 0。
  • max="100":设置范围的最大值为 100。
  • step="10":设置滑动的步长为 10。意味着用户只能选择 0, 10, 20, …, 100 的值。

3. 显示当前值

为了让用户更清楚选择的当前值,你可以使用 JavaScript 来显示当前的滑块值。

<div class="mb-3">
  <label for="customRange3" class="form-label">Range with current value</label>
  <input type="range" class="form-range" id="customRange3" min="0" max="100" step="1">
  <output for="customRange3" id="rangeOutput">50</output>
</div>

<script>
  const rangeInput = document.getElementById("customRange3");
  const rangeOutput = document.getElementById("rangeOutput");
  
  rangeInput.addEventListener("input", function() {
    rangeOutput.textContent = rangeInput.value;
  });
</script>

  • <output>:用来显示当前的滑块值。
  • input 事件监听器:当用户调整滑块时,更新显示的值。

4. 自定义颜色和样式

如果你希望自定义滑块的颜色或样式,你可以使用 CSS。

<div class="mb-3">
  <label for="customRange4" class="form-label">Custom Colored Range</label>
  <input type="range" class="form-range" id="customRange4" min="0" max="100" step="1">
</div>

<style>
  #customRange4 {
    background: linear-gradient(to right, #4e73df 0%, #4e73df 50%, #e74a3b 50%, #e74a3b 100%);
  }
</style>

  • background: linear-gradient:使用渐变来改变滑块的颜色区域。你可以使用 CSS 来调整颜色和样式,使其符合你的设计需求。

5. 带有标签的选择区间

你可以在滑块的两侧添加标签,显示当前选择的数值范围。

<div class="mb-3">
  <label for="customRange5" class="form-label">Range with labels</label>
  <input type="range" class="form-range" id="customRange5" min="0" max="100" step="1" value="50">
  <div class="d-flex justify-content-between">
    <span>0</span>
    <span>50</span>
    <span>100</span>
  </div>
</div>

  • <div class="d-flex justify-content-between">:使用 Bootstrap 的 Flexbox 类来使标签在滑块下方均匀分布。
  • <span>:为滑块设置不同的标签,标明每个数值区间的标识。

6. 禁用选择区间

你可以禁用选择区间,使其不可操作。

<div class="mb-3">
  <label for="disabledRange" class="form-label">Disabled Range</label>
  <input type="range" class="form-range" id="disabledRange" min="0" max="100" step="1" disabled>
</div>

  • disabled:禁用滑块,用户无法与之交互。

总结

Bootstrap 5 中,选择区间(Range Input)提供了一个非常简洁和现代化的界面来进行数值选择。通过简单的 HTML 结构和 Bootstrap 的内建类,开发者可以快速创建可自定义、响应式的滑块控件。你还可以根据需求,使用 JavaScript 来显示当前值,调整样式,或通过 CSS 自定义外观。