我有一个 HTML 输入。当用户在其中输入内容时,我设置了“输入”事件来处理将输入更新为用户输入内容的过滤版本(以及更新选择开始和选择结束以实现流畅的用户体验)。为了达到适当的效果,这种情况会不断发生。
然而,我注意到,每当 JS 通过设置输入的值时input.value = '...';
,输入的撤消历史记录似乎消失了。也就是说,在聚焦的情况下按 Ctrl-Z 不再返回到之前的状态。
有什么方法可以提供输入自定义撤消历史记录,或者以其他方式防止它丢失历史记录,同时仍然更改其值?
这是我的问题的一个最小示例:
输入顶部输入(基本在每个字符之间添加句点)后,Ctrl-Z 不会撤消。
<body>
<input type="text" id="textbox" placeholder="No undo"/><br/>
<input type="text" id="textbox2" placeholder="Undo"/>
<script>
var tbx = document.getElementById("textbox");
tbx.addEventListener('input', () => {
tbx.value = tbx.value + '.'
});
</script>
</body>
You can try storing the input's previous value in a variable, then listen for the Ctrl + Z key combination in a keydown
event listener attached to the input. When it is fired, you can set the value of the input to the previous stored value.
btn.addEventListener('click', function() {
savePrevInput(input.value)
input.value = "Hello World!";
})
var prevInput;
function savePrevInput(input) {
prevInput = input;
}
input.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 90) {
if (prevInput) {
input.value = prevInput;
input.selectionStart = prevInput.length;
}
}
})
<input id="input" />
<button id="btn">Change</button>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)