gpt4 book ai didi

javascript - 如何防止用户拖动 HTML 输入类型 ='range' 对?

转载 作者:行者123 更新时间:2023-11-28 04:58:28 27 4
gpt4 key购买 nike

我有三个 input type='range' 字段,它们具有不同的最大值但共享相同的容量。每次更改三个输入中的任何一个时,此容量都会降低。当容量达到 0 时,我应该防止输入字段向右移动(增加它们的值)并且只向左移动,但我不知道如何使用 JS 和 jQuery 做到这一点

这里是输入的html

<input type="range" class="slider" id="woodSlider" min="0" value="0" max="1558">
<input type="range" class="slider" id="ironSlider" min="0" value="0" max="2555">
<input type="range" class="slider" id="stoneSlider" min="0" value="0" max="2451">

下面是降低容量的代码:

$("input").change(function() {  
$("#capacityLeft").html(parseInt(holding.capacity) -
$("#woodSlider").val() -
$("#ironSlider").val() -
$("#stoneSlider").val());
if(parseInt($("#capacityLeft").html()) <= 0) {
// TODO: FIND OUT HOW TO STOP THE SLIDERS FROM MOVING
}
});

最佳答案

好的,所以您可以使用 event.preventDefault() 来停止事件。您应该将函数绑定(bind)到这些范围 slider 上的 onchangeoninput 事件并计算总和,检查它是否超过最大值,如果超过则停止该事件。

Here's a pure JS solution ( fiddle 链接),可以很容易地用 jQuery 重写。

var maxTotal = 150, // define the max sum of values
inputs = [].slice.call(document.getElementsByTagName('input')), // refrence to the elements
getTotal = function(){ // helper function to calculate the sum
var sum = 0;
inputs.forEach( function(input){
sum += parseInt(input.value, 10);
});
return sum;
},
maxReached = function(e){ // check if the max is reached
var sum = getTotal(), target;
if(sum > maxTotal){
target = e.target;
// set the max possible value if the user, for example, clicks too far to the right
target.value = target.value - (sum - maxTotal);
// next line is just for demonstrational purposes
document.getElementById('total').innerHTML = getTotal();

// prevent increasing the value
e.preventDefault();
return false;
}
// next line is just for demonstrational purposes
document.getElementById('total').innerHTML = getTotal();

// everything's fine, nothing to do.
return true;
};

// attach the maxReached function to your inputs
inputs.forEach( function(input){
input.addEventListener('input', maxReached );
});

关于javascript - 如何防止用户拖动 HTML 输入类型 ='range' 对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19089653/

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