<input type="range">

range 类型的 <input> 元素允许用户指定一个数值,该数值必须不小于给定值,且不大于另一个给定值。然而,精确值并不重要。这通常使用滑块或转盘控件来表示,而不是像 number 输入类型那样使用文本输入框。

¥<input> elements of type range let the user specify a numeric value which must be no less than a given value, and no more than another given value. The precise value, however, is not considered important. This is typically represented using a slider or dial control rather than a text entry box like the number input type.

由于这种小部件不精确,因此仅当控件的确切值不重要时才应使用它。

¥Because this kind of widget is imprecise, it should only be used if the control's exact value isn't important.

Try it

如果用户的浏览器不支持 range 类型,它将回退并将其视为 text 输入。

¥If the user's browser doesn't support type range, it will fall back and treat it as a text input.

验证

¥Validation

没有可用的模式验证;但是,会执行以下形式的自动验证:

¥There is no pattern validation available; however, the following forms of automatic validation are performed:

  • 如果 value 设置为无法转换为有效浮点数的值,则验证会失败,因为输入存在错误输入。
  • 该值不会小于 min。默认值为 0。
  • 该值不会大于 max。默认值为 100。
  • 该值将是 step 的倍数。默认值为 1。

¥Value

value 属性包含一个字符串,其中包含所选数字的字符串表示形式。该值绝不是空字符串 ("")。默认值是指定的最小值和最大值之间的中间值,除非最大值实际上小于最小值,在这种情况下,默认值设置为 min 属性的值。确定默认值的算法是:

¥The value attribute contains a string which contains a string representation of the selected number. The value is never an empty string (""). The default value is halfway between the specified minimum and maximum—unless the maximum is actually less than the minimum, in which case the default is set to the value of the min attribute. The algorithm for determining the default value is:

js
defaultValue =
  rangeElem.max < rangeElem.min
    ? rangeElem.min
    : rangeElem.min + (rangeElem.max - rangeElem.min) / 2;

如果尝试将该值设置为低于最小值,则会将其设置为最小值。同样,尝试将值设置为高于最大值会导致该值被设置为最大值。

¥If an attempt is made to set the value lower than the minimum, it is set to the minimum. Similarly, an attempt to set the value higher than the maximum results in it being set to the maximum.

附加属性

¥Additional attributes

除了所有 <input> 元素共享的属性外,范围输入还提供以下属性。

¥In addition to the attributes shared by all <input> elements, range inputs offer the following attributes.

注意:以下输入属性不适用于输入范围:acceptaltcheckeddirnameformactionformenctypeformmethodformnovalidateformtargetheightmaxlengthminlengthmultiplepatternplaceholderreadonlyrequiredsizesrc。任何这些属性(如果包含)都将被忽略。

¥Note: The following input attributes do not apply to the input range: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, readonly, required, size, and src. Any of these attributes, if included, will be ignored.

list

list 属性的值是位于同一文档中的 <datalist> 元素的 id<datalist> 提供了一个预定义值列表来建议用户进行此输入。列表中与 type 不兼容的任何值都不包含在建议选项中。提供的值是建议,而不是要求:用户可以从此预定义列表中进行选择或提供不同的值。

¥The value of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

有关如何在支持的浏览器中表示范围内的选项的示例,请参阅下面的 添加刻度线

¥See the adding tick marks below for an example of how the options on a range are denoted in supported browsers.

max

允许值范围内的最大值。如果输入到元素中的 value 超过此值,则该元素将失败 约束验证。如果 max 属性的值不是数字,则该元素没有最大值。

¥The greatest value in the range of permitted values. If the value entered into the element exceeds this, the element fails constraint validation. If the value of the max attribute isn't a number, then the element has no maximum value.

该值必须大于或等于 min 属性的值。请参阅 HTML max 属性。

¥This value must be greater than or equal to the value of the min attribute. See the HTML max attribute.

min

允许值范围内的最低值。如果元素的 value 小于此值,则该元素未通过 约束验证。如果为 min 指定的值不是有效数字,则输入没有最小值。

¥The lowest value in the range of permitted values. If the value of the element is less than this, the element fails constraint validation. If a value is specified for min that isn't a valid number, the input has no minimum value.

该值必须小于或等于 max 属性的值。请参阅 HTML min 属性。

¥This value must be less than or equal to the value of the max attribute. See the HTML min attribute.

注意:如果 minmax 值相等或 max 值低于 min 值,则用户将无法与该范围交互。

¥Note: If the min and max values are equal or the max value is lower than the min value the user will not be able to interact with the range.

step

step 属性是一个数字,指定值必须遵循的粒度。仅与指定步进间隔匹配的值(如果指定则为 min,否则为 value,如果未提供则为适当的默认值)才有效。

¥The step attribute is a number that specifies the granularity that the value must adhere to. Only values that match the specified stepping interval (min if specified, value otherwise, or an appropriate default value if neither of those is provided) are valid.

step 属性也可以设置为 any 字符串值。此 step 值意味着不暗示步进间隔,并且指定范围内允许任何值(除非其他约束,例如 minmax)。请参阅 将步长设置为 any 示例,了解其在支持的浏览器中的工作原理。

¥The step attribute can also be set to the any string value. This step value means that no stepping interval is implied and any value is allowed in the specified range (barring other constraints, such as min and max). See the Setting step to the any value example for how this works in supported browsers.

注意:当用户输入的值不符合步进配置时,user agent 可能会将值四舍五入到最接近的有效值,当有两个同样接近的选项时,更倾向于将数字向上舍入。

¥Note: When the value entered by a user doesn't adhere to the stepping configuration, the user agent may round off the value to the nearest valid value, preferring to round numbers up when there are two equally close options.

range 输入的默认步进值为 1,仅允许输入整数,除非步进基数不是整数;例如,如果将 min 设置为 -10,将 value 设置为 1.5,则 step 为 1 将仅允许正方向上的值,例如 1.5、2.5、3.5、… 以及正方向上的 -0.5、-1.5、-2.5、… 等值。 负方向。参见 HTML step 属性

¥The default stepping value for range inputs is 1, allowing only integers to be entered, unless the stepping base is not an integer; for example, if you set min to -10 and value to 1.5, then a step of 1 will allow only values such as 1.5, 2.5, 3.5,… in the positive direction and -0.5, -1.5, -2.5,… in the negative direction. See the HTML step attribute.

非标准属性

¥Non-standard attributes

orient

与影响 <progress><meter> 元素的 -moz-orient 非标准 CSS 属性类似,orient 属性定义范围滑块的方向。值包括 horizontal(表示范围水平呈现)和 vertical(表示范围垂直呈现)。

¥Similar to the -moz-orient non-standard CSS property impacting the <progress> and <meter> elements, the orient attribute defines the orientation of the range slider. Values include horizontal, meaning the range is rendered horizontally, and vertical, where the range is rendered vertically.

示例

¥Examples

虽然 number 类型允许用户输入带有可选约束的数字,强制其值介于最小值和最大值之间,但它确实要求用户输入特定值。range 输入类型允许你在用户可能不关心(或不知道)所选的具体数值是什么的情况下询问用户一个值。

¥While the number type lets users enter a number with optional constraints forcing their value to be between a minimum and a maximum value, it does require that they enter a specific value. The range input type lets you ask the user for a value in cases where the user may not even care—or know—what the specific numeric value selected is.

常用范围输入的一些情况示例:

¥A few examples of situations in which range inputs are commonly used:

  • 音频控制,例如音量和平衡,或过滤器控制。
  • 颜色配置控件,例如颜色通道、透明度、亮度等。
  • 游戏配置控制,例如难度、可见距离、世界大小等。
  • 密码管理器生成的密码的密码长度。

通常,如果用户对最小值和最大值之间的距离百分比比实际数字本身更感兴趣,则范围输入是一个很好的选择。例如,在家庭立体声音量控制的情况下,用户通常会想到 "将音量设置为最大音量的一半" 而不是 "将音量设置为 0.5"。

¥As a rule, if the user is more likely to be interested in the percentage of the distance between minimum and maximum values than the actual number itself, a range input is a great candidate. For example, in the case of a home stereo volume control, users typically think "set volume at halfway to maximum" instead of "set volume to 0.5".

指定最小值和最大值

¥Specifying the minimum and maximum

默认情况下,最小值为 0,最大值为 100。如果这不是你想要的,你可以通过更改 min 和/或 max 属性的值轻松指定不同的边界。这些可以是任何浮点值。

¥By default, the minimum is 0 and the maximum is 100. If that's not what you want, you can easily specify different bounds by changing the values of the min and/or max attributes. These can be any floating-point value.

例如,要要求用户输入 -10 到 10 之间的值,你可以使用:

¥For example, to ask the user for a value between -10 and 10, you can use:

html
<input type="range" min="-10" max="10" />

设置值的粒度

¥Setting the value's granularity

默认情况下,粒度为 1,这意味着该值始终是整数。要控制粒度,你可以更改 step 属性。例如,如果你需要一个介于 5 和 10 之间的值,则应将 step 的值设置为 0.5:

¥By default, the granularity is 1, meaning the value is always an integer. To control the granularity, you can change the step attribute. For example, If you need a value to be halfway between 5 and 10, you should set the value of step to 0.5:

设置步骤属性

¥Setting the step attribute

html
<input type="range" min="5" max="10" step="0.5" />

将步骤设置为 any

¥Setting step to any

如果你想接受任何值,无论它扩展到多少个小数位,你可以为 step 属性指定值 any

¥If you want to accept any value regardless of how many decimal places it extends to, you can specify a value of any for the step attribute:

HTML
html
<input id="pi_input" type="range" min="0" max="3.14" step="any" />
<p>Value: <output id="value"></output></p>

JavaScript
js
const value = document.querySelector("#value");
const input = document.querySelector("#pi_input");
value.textContent = input.value;
input.addEventListener("input", (event) => {
  value.textContent = event.target.value;
});

此示例允许用户选择 0 到 π 之间的任何值,而对所选值的小数部分没有任何限制。JavaScript 用于显示当用户与范围交互时值如何变化。

¥This example lets the user select any value between 0 and π without any restriction on the fractional part of the value selected. JavaScript is used to show how the value changes as the user interacts with the range.

添加刻度线

¥Adding tick marks

要向范围控件添加刻度线,请包含 list 属性,为其提供 <datalist> 元素的 id,该元素定义控件上的一系列刻度线。每个点都使用 <option> 元素表示,其 value 设置为应绘制标记的范围值。

¥To add tick marks to a range control, include the list attribute, giving it the id of a <datalist> element which defines a series of tick marks on the control. Each point is represented using an <option> element with its value set to the range's value at which a mark should be drawn.

HTML

html
<label for="temp">Choose a comfortable temperature:</label><br />
<input type="range" id="temp" name="temp" list="markers" />

<datalist id="markers">
  <option value="0"></option>
  <option value="25"></option>
  <option value="50"></option>
  <option value="75"></option>
  <option value="100"></option>
</datalist>

结果

¥Result

对多个范围控件使用相同的数据列表

¥Using the same datalist for multiple range controls

为了帮助你避免重复代码,你可以将相同的 <datalist> 重用于多个 <input type="range"> 元素和其他 <input> 类型。

¥To help you from repeating code you can reuse that same <datalist> for multiple <input type="range"> elements, and other <input> types.

注意:如果你还想要 显示标签(如下例所示),那么你将需要为每个范围输入一个 datalist

¥Note: If you also want to show the labels as in the example below then you would need a datalist for each range input.

HTML

html
<p>
  <label for="temp1">Temperature for room 1:</label>
  <input type="range" id="temp1" name="temp1" list="values" />
</p>
<p>
  <label for="temp2">Temperature for room 2:</label>
  <input type="range" id="temp2" name="temp2" list="values" />
</p>

<p>
  <label for="temp3">Temperature for room 3:</label>
  <input type="range" id="temp3" name="temp3" list="values" />
</p>

<datalist id="values">
  <option value="0" label="0"></option>
  <option value="25" label="25"></option>
  <option value="50" label="50"></option>
  <option value="75" label="75"></option>
  <option value="100" label="100"></option>
</datalist>

结果

¥Result

添加标签

¥Adding labels

你可以通过为 <option> 元素提供 label 属性来标记刻度线。但默认情况下不会显示标签内容。你可以使用 CSS 来显示标签并正确定位它们。这是你可以执行此操作的一种方法。

¥You can label tick marks by giving the <option> elements label attributes. However, the label content will not be displayed by default. You can use CSS to show the labels and to position them correctly. Here's one way you could do this.

HTML

html
<label for="tempB">Choose a comfortable temperature:</label><br />
<input type="range" id="tempB" name="temp" list="values" />

<datalist id="values">
  <option value="0" label="very cold!"></option>
  <option value="25" label="cool"></option>
  <option value="50" label="medium"></option>
  <option value="75" label="getting warm!"></option>
  <option value="100" label="hot!"></option>
</datalist>

CSS

css
datalist {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  writing-mode: vertical-lr;
  width: 200px;
}

option {
  padding: 0;
}

input[type="range"] {
  width: 200px;
  margin: 0;
}

结果

¥Result

创建垂直范围控件

¥Creating vertical range controls

默认情况下,浏览器将范围输入呈现为滑块,旋钮左右滑动。

¥By default, browsers render range inputs as sliders with the knob sliding left and right.

要创建拇指上下滑动的垂直范围,请将 writing-mode 属性设置为 vertical-rlvertical-lr 值:

¥To create a vertical range wherein the thumb slides up and down, set the writing-mode property with a value of either vertical-rl or vertical-lr:

html
<input type="range" min="0" max="10" value="8" />
css
input[type="range"] {
  writing-mode: vertical-lr;
}

这会导致范围滑块垂直渲染:

¥This causes the range slider to render vertically:

如果你想支持旧版本的 Chrome 和 Safari,还可以将 CSS appearance 属性设置为非标准 slider-vertical 值,并包含非标准 orient="vertical" 属性以支持旧版本的 Firefox。

¥You can also set the CSS appearance property to the non-standard slider-vertical value if you want to support older versions of Chrome and Safari, and include the non-standard orient="vertical" attribute to support older versions of Firefox.

示例请参见 创建垂直表单控件

¥See Creating vertical form controls for examples.

技术总结

¥Technical summary

包含所选数值的字符串表示形式的字符串;使用 valueAsNumber 获取数字值。
活动 changeinput
支持的通用属性 autocompletelistmaxminstep
IDL 属性 listvaluevalueAsNumber
DOM 接口

HTMLInputElement

方法 stepDown()stepUp()
隐式 ARIA 角色 slider

规范

Specification
HTML Standard
# range-state-(type=range)

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看