【问题标题】:Change value of range slider dynamically动态更改范围滑块的值
【发布时间】:2019-03-28 20:34:07
【问题描述】:

我有一些带有 input[type="text"] 和 input[type="range"] 的 div。

<div class="box">
    <input type="text" value="10">
    <input type="range" min="0" value="0" max="18" step="1">
</div>
<div class="box">
    <input type="text" value="10">
    <input type="range" min="0" value="0" max="18" step="1">
</div>

在一些 jQuery 的帮助下,范围滑块的步长不均匀,并且文本输入字段的值在移动滑块时会发生变化。

如果您在输入字段中输入数字,该数字将更改为最接近的步长/值。

stepVal = [10, 35, 50, 90, 100, 135, 155, 170, 190, 220, 230, 250, 270, 290, 310, 320, 350, 365, 400];
$('.box').each(function() {
  $(this).on('input', 'input[type="range"]', function() {
    $(this).prev('input[type=text]').val(stepVal[this.value]);
  });
  $(this).on('blur', 'input[type="text"]', function() {
    var textVal = $(this).val();
    var closestVal = stepVal.reduce(function(prev, curr) {
      return (Math.abs(curr - textVal) < Math.abs(prev - textVal) ? curr : prev);
    });
    $(this).val(closestVal);
    $(this).next('input[type=range]').val(closestVal);
  });
});

问题是范围滑块仅移动到末尾或中间,而不是输入的步长/值。任何想法如何解决这个问题?

【问题讨论】:

    标签: javascript jquery html input html-input


    【解决方案1】:

    您的问题是当您在输入文本中输入value 时,您将错误的value 设置为range

    因为您将值设置为closestVal,而它应该是closestVal 的相应index,这就是为什么当closestValue10 时它只到达中间而其他高于max 的值。

    解决方案:

    你需要改变这个:

    $(this).next('input[type=range]').val(closestVal);
    

    当您在input 中输入一个值时,要从您的stepVal 数组中获取该值的索引。

    $(this).next('input[type=range]').val(stepVal.indexOf(closestVal));
    

    演示:

    stepVal = [10, 35, 50, 90, 100, 135, 155, 170, 190, 220, 230, 250, 270, 290, 310, 320, 350, 365, 400];
    $('.box').each(function() {
      $(this).on('input', 'input[type="range"]', function() {
        $(this).prev('input[type=text]').val(stepVal[this.value]);
      });
      $(this).on('blur', 'input[type="text"]', function() {
        var textVal = $(this).val();
        var closestVal = stepVal.reduce(function(prev, curr) {
          return (Math.abs(curr - textVal) < Math.abs(prev - textVal) ? curr : prev);
        });
        $(this).val(closestVal);
        $(this).next('input[type=range]').val(stepVal.indexOf(closestVal));
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="box">
        <input type="text" value="10">
        <input type="range" min="0" value="0" max="18" step="1">
    </div>
    <div class="box">
        <input type="text" value="10">
        <input type="range" min="0" value="0" max="18" step="1">
    </div>

    【讨论】:

    • 您的代码 sn-p » missing 中有一点错误)但您是对的,这就是解决方案。谢谢。
    • @stewe1da 这只是一个复制/粘贴错字;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多