答案 0 :(得分:2)
您可以先获取所有元素,然后在focus
上添加一个类,然后在blur
上将其删除。此类将用于定位其余元素并更新其值
//get all the input with specified name and add event lister to it
[...document.getElementsByName('userInp')].forEach(function(item) {
// on focusing adding a class to the current target
item.addEventListener("focus", function(e) {
e.target.classList.add('focus')
});
// removing the class on blurring from current target
item.addEventListener("blur", function(e) {
e.target.classList.remove('focus')
});
item.addEventListener('keyup', function(e) {
// get the value from the target input
let getVal = e.target.value;
if (getVal < 100) {
// devide equally among rest of the inputs for this example it is 3
let eachVal = (100 - getVal) / 3
// then select all the input which does not have class focus
// and update their value
document.querySelectorAll("input:not(.focus)").forEach(function(elem) {
elem.value = eachVal.toFixed(2)
})
}
})
})
<input type='text' name='userInp' value='25'>
<input type='text' name='userInp' value='25'>
<input type='text' name='userInp' value='25'>
<input type='text' name='userInp' value='25'>