使用 oninput 事件处理程序和 onkeyup/onkeydown 作为其回退
HTML5 标准化了 oninput
事件处理程序,它应该用于检测 JavaScript 中的用户输入。 当然,我们可以改用 onkeydown
或 onkeyup
,但它们从来都不是真正为这个特定用例设计的,它显示了这一点。
幸运的是,所有现代浏览器都支持 oninput
,包括 IE9。 例如,对于较旧的浏览器,回退到 keydown
事件是个好主意。 不幸的是,检测 oninput
支持并不像你想象的那么简单。 我假设这个 JavaScript 片段会返回 true 或 false,这取决于是否支持 oninput
:
'oninput' in document.createElement('input');
这在大多数浏览器中都能正常工作,但在 Firefox 中却不行。 虽然仍然可以为 oninput
编写一个可用的功能测试,但这真的很麻烦。
此外,不需要功能测试——只需将处理程序绑定到输入和按键事件,然后在 oninput
处理程序触发后立即删除 onkeydown
处理程序。 这是一个简单的示例,DOM0 样式:
someElement.oninput = function() {
this.onkeydown = null;
// Your code goes here
};
someElement.onkeydown = function() {
// Your code goes here
};
keydown
事件只会触发一次(因为它在 oninput
之前触发)——之后,只会使用 oninput
。 这并不理想,但它肯定胜过添加一行又一行的代码以正确检测所有浏览器中的 oninput
支持。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。