HTML DOM 输入范围 step 属性

htmlweb developmentfront end technology更新于 2025/10/16 18:52:17

HTML DOM 输入范围 step 属性用于设置或返回滑块控件 step 属性值。它指定滑块每次移动的距离。通过将 max 和 min 属性与 step 属性结合使用,我们可以定义一个合法值的范围。

语法

以下是语法 −

设置 step 属性 −

rangeObject.step=number

此处,number 指定滑块控件的移动距离。默认值为 1。

示例

让我们来看一个输入范围 step 属性的示例 −

<!DOCTYPE html>
<html>
<body>
<h1>Input range step Property</h1>
<form>
VOLUME <input type="range" id="RANGE1" name="VOL">
</form>
<p>Change the step property value of the above range control by clicking the below button</p>
<button type="button" onclick="changeStep()">CHANGE</button>
<p id="Sample"></p>
<script>
   function changeStep() {
      document.getElementById("RANGE1").step ="30" ;
      document.getElementById("Sample").innerHTML = "The step attribute value is now 30";
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"更改"按钮时 −

在上面的例子中 −

我们在表单中创建了一个输入字段,其 type=“range”、id=“RANGE1”、name=“VOL”。其 step 属性值默认设置为 1 −

<form>
VOLUME <input type="range" id="RANGE1" name="VOL">
<form>

然后我们创建了一个按钮"CHANGE",当用户点击该按钮时,它会执行 changeStep() 方法 −

<button type="button" onclick="changeStep()">CHANGE</button>

changeStep() 方法使用 getElementById() 方法获取类型为 range 的输入字段,并将 id 传递给该字段 "RANGE1"。获取该元素后,我们将其 step 属性设置为 30。这将增加滑块单次移动的距离。由于默认最小值为 0,最大值为 100,因此滑块现在只会移动三个位置 −

function changeStep() {
   document.getElementById("RANGE1").step ="30" ;
   document.getElementById("Sample").innerHTML = "The step attribute value is now 30";
}

相关文章


有用资源