首页 > 解决方案 > 多个 HTML 输入范围类型的标签总是加起来一个特定的值?

问题描述

我希望有多个类型范围的 HTML 输入标签,它们总是加起来为一个特定的值。这是我当前的代码:

<label>Slider 1
    <input max="1.0" min="-1.0" step="0.05" type="range" value="1.0">
</label>
<label>Slider 2
    <input max="1.0" min="-1.0" step="0.05" type="range" value="0.0">
</label>
<label>Slider 3
    <input max="1.0" min="-1.0" step="0.05" type="range" value="0.0">
</label>
<label>Slider 4
    <input max="1.0" min="-1.0" step="0.05" type="range" value="0.0">
</label>

我想拥有它,以便如果一个滑块移动,其余的会被调整,以便计数/总和始终为 1。我不介意使用 JavaScript(但最好不要),但我不想使用jQuery、jQuery-UI 或其他外部库,这个类似的问题询问:多个 jQuery-UI 滑块的组合总数

标签: javascripthtmlforms

解决方案


我们将使用纯 JS 来完成这项工作。您要添加的第一件事是onchange滑块的属性,因此它会触发将更新其他滑块的给定函数。我们必须给这个函数我们刚刚改变的滑块的索引。让滑块索引介于 0 和 3 之间。给它们一个 ID,以便我们能够在 JS 脚本中更改它们。让我们调用函数change()

所以现在让我们编写函数。我们要做的是改变其他滑块的值。初始总和是 1,所以让我们永远保持这个值。我们需要将这些值存储在一个数组中,以便我们能够看到变化是什么。因此,当更改滑块时,计算新值和旧值之间的增量。一旦您知道更改如何影响总和,让我们更改其他滑块,这要归功于我们刚刚计算的增量。由于我们可以更改 3 个滑块,因此将它们添加到每个滑块的 delta 的三分之一。这样,对一个滑块所做的更改将在总和中“取消”,因此我们保留初始值,即 1。

这是您的代码现在的样子:

let values = [1, 0, 0, 0]; // The initial values

  /* The onchange attribute will trigger this function */
  function change(x) {

    let newValue = document.getElementById(String(x)).value * 1; // Find the new value
    let oldValue = values[x]; // Search for the old value
    
    values[x] = newValue; // Update in the array the new value
    let deltaValue = oldValue - newValue; // Calculate the difference between the old value and the new one

    /* Now, loop through all the buttons to update them */
    for(let i = 0; i < 4; i++) {
      if(i === x) continue; // If it's the same, so do not change a thing
      
      /* This is the new value we want to put in
       * We want to equilibrate the whole system
       * Means we have to update the 3 other sliders
       * So just add to each one of them the third of the difference created by the one changed
       */
      
      let newVal = document.getElementById(String(i)).value * 1 + deltaValue / 3; // * 1 is to convert the value into an number, we do not want a String
      document.getElementById(String(i)).value = newVal; // Put the new value in
      values[i] += deltaValue / 3; // And update that value in the array
    }
  }
<label>Slider 1
    <input onchange="change(0)" id="0" max="1.0" min="-1.0" step="0.05" type="range" value="1.0">
</label>
<label>Slider 2
    <input onchange="change(1)" id="1" max="1.0" min="-1.0" step="0.05" type="range" value="0.0">
</label>
<label>Slider 3
    <input onchange="change(2)" id="2" max="1.0" min="-1.0" step="0.05" type="range" value="0.0">
</label>
<label>Slider 4
    <input onchange="change(3)" id="3" max="1.0" min="-1.0" step="0.05" type="range" value="0.0">
</label>

我很确定可以进行很多优化,但是由于我不是 JS 专家,所以应该这样做!

希望这对您有所帮助。


推荐阅读