如何通过输入值更改滑块的值

时间:2019-04-20 09:12:39

标签: javascript

function myFunction() {
  var slider = document.getElementById("myRange").value;
  document.getElementById("myRangeValue").value = "Rs: " + slider;
}
<div class="wrapper Slider">
  <input type="range" min="0" max="10000000" value="20000" name="myRange" id="myRange" onchange="myFunction()" style="margin-top: 10px;">
</div>

<div class="wrapper SliderValue">
  <input type="text" name="myRangeValue" value="Rs.0" id="myRangeValue" style="height:50px;text-align: center;font-size: 25px;">
</div>

自从我滚动滑块以来,输入框中的值就会更改,但是如何通过提供输入值??来更改滑块的值?

假设输入值= 50000 所以, 滑块的值也将更改为50000,而无需滚动。

1 个答案:

答案 0 :(得分:0)

在此处输入滑块:

<div class="wrapper Slider">
    <input type="range" min="0" max="10000000" value="20000" class="slider " name="myRange" id="myRange" style="margin-top: 10px;">
</div>
<div class="wrapper SliderValue">  
    <input type="text" class="personal" name="myRangeValue" value="Rs.0"  id="myRangeValue" style="height:50px;text-align: center;font-size: 25px;">
</div>    

在myRangeValue inout框中单击return后,您可以使用以下javascript进行更新。

    document.getElementById('myRange').addEventListener('change', (evt) => {
        document.getElementById('myRangeValue').value = document.getElementById('myRange').value;
    });

    document.getElementById('myRange').addEventListener('mousemove', (evt) => {
        document.getElementById('myRangeValue').value = document.getElementById('myRange').value;
    });

    document.getElementById('myRangeValue').addEventListener("keyup", function (event) {
        if (event.keyCode !== undefined) { // Handle the event with KeyboardEvent.keyCode
            switch(event.keyCode) {
                case 13: // return key
                    event.preventDefault();
                    document.getElementById('myRange').value = document.getElementById('myRangeValue').value;
                    break;
                default:
                    // console.log('event.keyCode: ' + event.keyCode)
            }
        };
    });

这是一个演示上面代码的jsfiddle Change slider value