我有一个场景,我阻止用户输入小数点后的第二个数字。我在 keydown 事件上有我的代码。 下面是我的代码:
$scope.Inputkeydown = function (event, value) {
if (event.keyCode != 8) {
if (value != null && value != undefined && value != "") {
var regex = /^\d*\.\d$/; //this regex passes only decimal numbers with one digit after decimal
if (regex.test(value)) {
event.preventDefault();
}
}
}
};
现在的问题是,如果用户选择文本框中的文本(比如 50.0),然后说按 5,那么它也会被阻止,因为文本框中的值为 50.0 并且正则表达式允许它通过,并且它被阻止避免被输入。
我可以检查 keydown 是否正在复制文本吗?或者还有其他办法吗?
最佳答案
您可以在按键后将其删除,而不是阻止用户输入它:
function filterDecimals(inp) {
return inp.replace(/^(\d*\.\d)\d*$/g, '$1');
}
或者,如果您想删除其后的所有内容,请将第二个 \d*
替换为 .*
编辑(使用示例)
此函数将文本作为输入并返回新的过滤文本。要使用它,只需在 keypress
上附加一个事件处理程序,如下所示:
<input type="text" id="filteredbox">
<script>
var txt = document.getElementById("filteredbox");
// on keyup event (you can change to keypress if you want, but this is more logical here
txt.addEventListener("keyup", function(){
// sets value of txt to the returned data from filterDecimals()
// if statement: only filters it if necessary; this eliminates the "selected text" issue you mentioned
if (this.value !== filterDecimals(this.value)) {
this.value = filterDecimals(this.value);
}
});
</script>
关于javascript - 检查是否在 keydown 事件中选择了文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40214099/