gpt4 book ai didi

javascript - 多个范围类型的 HTML 输入标签总是加起来为特定值?

转载 作者:行者123 更新时间:2023-12-02 21:41:52 25 4
gpt4 key购买 nike

我想要有多个范围类型的 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>

我希望这样,如果一个 slider 移动,其余 slider 都会调整,以便计数/总和始终为 1。我不介意使用 JavaScript(但最好不要使用),但我不介意想要使用 jQuery、jQuery-UI 或其他外部库,这个类似的问题询问:Combined total for multiple jQuery-UI Sliders

最佳答案

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

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

希望这对您有帮助。

关于javascript - 多个范围类型的 HTML 输入标签总是加起来为特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60346323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com