多个HTML输入标签的类型范围总是累加到一个特定值?

问题描述 投票:0回答:1

我想拥有多个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或其他外部库,这个类似的问题会询问以下问题:Combined total for multiple jQuery-UI Sliders

javascript html forms
1个回答
0
投票

我们将使用普通的JS来完成这项工作。您要添加的第一件事是滑块的onchange属性,因此它将触发给定的函数,该函数将更新其他滑块。我们必须为该函数指定刚更改的滑块的索引。让滑块的索引在0到3之间。给它们一个ID,这样我们就可以在JS脚本中对其进行更改。让我们调用函数change()

所以让我们现在编写函数。我们要做的是更改其他滑块的值。初始总和为1,因此让我们永远保持该值。我们需要将值存储在数组中,以便能够看到更改是什么。因此,当更改滑块时,请计算新值和旧值之间的差值。一旦知道更改如何影响总和,就让我们更改其他滑块,这要归功于我们刚刚计算出的增量。由于我们可以更改3个滑块,因此请将它们的增量的三分之一添加到每个滑块中。这样,一个滑块上所做的更改将被“取消”,因此我们保留了初始值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专家,所以应该做到!

希望这对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.