首先,您应该将 a、b 和 c 的最大值设置为 36。
然后,您需要使用该onchange
事件来确保在更改它们时一个会影响另一个。
例如:
如果 a = 20,b=10,c=6,则 d=36
如果增加 c,使其变为 7,则 a 应变为 19.5,b 应变为 9.5
HTML
<input type="number" id="a" max="36" value="12" onchange="Stabilized(this)" class="numbers">
<input type="number" id="b" max="36" value="12" onchange="Stabilized(this)" class="numbers">
<input type="number" id="c" max="36" value="12" onchange="Stabilized(this)" class="numbers">
<input type="number" id="d" max="36" value="36">
JavaScript
function Stabilized(e)
{
var thisNumber = e.value;
var totalSum=0;
var i;
var remainingSum = 36 - parseFloat(thisNumber);
var numbersList = document.getElementsByClassName("numbers");
var currentRemainingSum=0;
var average;
var y=0;
var flag1=0;
var counter=0;
for (i=0;i<numbersList.length;i++)
{
totalSum +=parseFloat(numbersList[i].value);
if(numbersList[i]!=e)
{
y++
currentRemainingSum = parseFloat(currentRemainingSum) + (parseFloat(numbersList[i].value));
}
}
if((parseFloat(currentRemainingSum))>(parseFloat(remainingSum)))
{
average = ((currentRemainingSum-remainingSum)/y);
while(parseFloat(currentRemainingSum)>parseFloat(remainingSum)){
for (i=0;i<numbersList.length;i++)
{
if(numbersList[i]!=e)
{
if((parseFloat(numbersList[i].value))>=average){
numbersList[i].value = (parseFloat(numbersList[i].value) - parseFloat(average));
remainingSum=parseFloat(remainingSum)+parseFloat(average);
}
else
{
remainingSum=(parseFloat(remainingSum)+(parseFloat(numbersList[i].value)));
numbersList[i].value = 0;
}
}
if((parseFloat(currentRemainingSum)<=parseFloat(remainingSum))){
break;
}
}
}
}
else if((parseFloat(currentRemainingSum))<(parseFloat(remainingSum)))
{
average = ((remainingSum-currentRemainingSum)/y)
for (i=0;i<numbersList.length;i++)
{
if(numbersList[i]!=e)
{
counter++;
if(numbersList[i].value==36)
{
flag1++;
}
else
{
numbersList[i].value = (parseFloat(numbersList[i].value) + average);
remainingSum = remainingSum - average;
flag1--;
}
}
if((parseFloat(remainingSum))<=0 || (flag1==counter && numbersList.length==(i+1))){
break;}
}
}
}
演示