有一个输入字段,当用户输入任何全角日语字符(仅限数字)时,它不会显示在该输入字段上。它将转换为其各自的半角字符,然后该半角字符将在同一输入字段中可见。 如果用户输入
0
,这个 0
将不会显示在输入字段中,它将显示转换后的半角 0。在我的例子中,问题是如果用户输入 0
,该函数将运行两次并显示00
,但应该只是0
。有人可以帮我解决一下吗?
<input type="text" id="inputField" oninput="convertToHalfWidth(this.value)">
<script>
function convertToHalfWidth(input) {
console.log(input);
// Map of full-width to half-width numbers
const fullToHalfMap = {
'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9'
};
// Replacing full-width numbers with their half-width counterparts
const convertedInput = input.replace(/[0-9]/g, match => fullToHalfMap[match]);
// Updating the input field with the converted value
document.getElementById('inputField').value = convertedInput;
}
</script>
根据规格:
合成的开始通过调度合成开始事件来标记。在撰写会话期间,每当文本撰写系统更新其活动文本段落时,就会调度compositionupdate 事件。
问题是每当
a 组合会话开始/更新/完成时,都会出现类型为
insertCompositionText
的输入事件。即使对于简单的全角字符(例如数字和空格)不需要使用 IME 窗口组成的多个符号,仍然会由 compositionstart
和
compositionend
触发两个输入事件。
请注意,通过粘贴完整字符不会重现此问题,因为不会启动任何组合会话。只会启动类型为
insertText
的输入事件。
一种解决方案是使用
onkeyup
事件代替。
const inputField = document.getElementById('inputField');
const fullToHalfMap = {
'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9'
};
inputField.addEventListener('compositionend', function (e) {
const input = e.target.value;
// Replacing full-width numbers with their half-width counterparts
const convertedInput = input.replace(/[0-9]/g, match => fullToHalfMap[match]);
// Updating the input field with the converted value
console.log(document.getElementById('inputField').value, "updated")
document.getElementById('inputField').value = convertedInput;
})
<input type="text" id="inputField">
你太接近了!我认为问题在于 0
被转换为零,但我无法验证这一点。我也没有看到您描述的
00
输出(如果重要的话,我正在使用 Firefox)。然而,我确实观察到没有进行任何更换。这是通过强制匹配输出到带有 match.toString()
的字符串来解决的
function convertToHalfWidth(input) {
console.log(input);
// Map of full-width to half-width numbers
const fullToHalfMap = {
'0': '0', '1': '1', '2': '2', '3': '3', '4': '4',
'5': '5', '6': '6', '7': '7', '8': '8', '9': '9'
};
// Replacing full-width numbers with their half-width counterparts
const convertedInput = input.replace(/[0-9]/g,
match => fullToHalfMap[match.toString()]);
// Updating the input field with the converted value
document.getElementById('inputField').value = convertedInput;
}
<input type="text" id="inputField" oninput="convertToHalfWidth(this.value)">