在JavaScript中,如果你希望一个输入框只能输入负数,可以通过多种方式实现。以下是一些方法和相关概念:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Only Negative Numbers</title>
</head>
<body>
<input type="number" id="negativeNumber" min="-999999" oninput="validateNegative(this)">
<script>
function validateNegative(input) {
if (input.value !== "" && parseInt(input.value) >= 0) {
input.value = "";
alert("Please enter a negative number.");
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Only Negative Numbers</title>
</head>
<body>
<input type="text" id="negativeNumber" onkeypress="return event.charCode >= 45 && event.charCode <= 57" onblur="validateNegative(this)">
<script>
function validateNegative(input) {
const regex = /^-?\d*$/;
if (!regex.test(input.value) || parseInt(input.value) >= 0) {
input.value = "";
alert("Please enter a valid negative number.");
}
}
</script>
</body>
</html>
通过结合HTML属性和JavaScript验证,可以有效地限制用户只能输入负数。这种方法不仅提高了数据的准确性,还增强了用户体验。
领取专属 10元无门槛券
手把手带您无忧上云