2013-05-02 81 views
0

如何在不限制输入值的情况下将输出值限制在5至195之间?如何在不限制输入值的情况下限制输入计算值?

<!DOCTYPE html> 
<html> 
<body> 

<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0 
<input type="range" id="a" value="50">100 + 
<input type="number" id="b" value="50">= 
<output name="x" for="a b"></output> 
</form> 

</body> 
</html> 

回答

1
<!DOCTYPE html> 
<html> 
<body> 

<form oninput="var n = parseInt(a.value)+parseInt(b.value); x.value = n < 5 ? 5 : (n > 195 ? 195 : n);">0 
<input type="range" id="a" value="50">100 + 
<input type="number" id="b" value="50">= 
<output name="x" for="a b"></output> 
</form> 

</body> 
</html> 

此使用嵌套三元算子的a ? b : c基本上是a if b else c。当它嵌套时,可以这样想:a ? b : (c ? d : e)作为a if b ELSE (c if d else e)由于(c ? d : e)等于ca ? b : c

试试吧here

Alternativley,你可以做

<form oninput="x.value = Math.min(Math.max(5,parseInt(a.value)+parseInt(b.value)),195);"/> 

其实现同样的结果,只是以不同的方式,你可以用它玩here

尝试一下这里: JSfiddle

+0

谢谢HennyH!这两个解决方案的作品,并感谢解释嵌套三元运算符。 – unogeo 2013-05-02 16:54:51