<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" id="input"/>
<script>
function check (e) {
var num = document.getElementById(e).value;
// console.log($(e).val());
// console.log(document.getElementById(e).value);
num += '';
num = num.replace(/[^0-9|\.]/g, ''); // 清除字符串中的非数字非.字符
if (/^0+/) {
// 清除字符串开头的0
num = num.replace(/^0+/, '');
}
if (!/\./.test(num)) {
// 为则行数字符串在末尾添加.0000
num += '.0000';
}
if (/^\./.test(num)) {
// 字符以.开头时,在开头添加0
num = '0' + num;
}
num += '0000'; // 在字符串末尾补零
num = num.match(/\d+\.\d{4}/)[0];
document.getElementById(e).value = num;
document.getElementById(e).value = num
// $(e).val(num);
// console.log($(e).val(num));
// console.log(document.getElementById(e).value = num);
}
let inp = document.querySelector('input');
inp.oninput = function () {
check("input");
document.onclick = function(e) {
if (e.target.tagName == "INPUT") {
console.log(getCursortPosition(inp));
}
}
}
// 获取文本域的光标位置
function getCursortPosition(obj) {
var cursorIndex = 0;
if (document.selection) {
// IE Support
obj.focus();
var range = document.selection.createRange();
range.moveStart('character', -obj.value.length);
cursorIndex = range.text.length;
} else if (obj.selectionStart || obj.selectionStart == 0) {
// another support
cursorIndex = obj.selectionStart;
}
return cursorIndex;
}
</script>
</body>
</html>
JS文本框只能输入四位小数点
于 2022-03-02 14:04:05 首次发布