迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 >

使用 oninput 事件处理程序和 onkeyup/onkeydown 作为其回退

作者:迹忆客 最近更新:2023/01/10 浏览次数:

HTML5 标准化了 oninput 事件处理程序,它应该用于检测 JavaScript 中的用户输入。 当然,我们可以改用 onkeydownonkeyup,但它们从来都不是真正为这个特定用例设计的,它显示了这一点。

幸运的是,所有现代浏览器都支持 oninput,包括 IE9。 例如,对于较旧的浏览器,回退到 keydown 事件是个好主意。 不幸的是,检测 oninput 支持并不像你想象的那么简单。 我假设这个 JavaScript 片段会返回 truefalse,这取决于是否支持 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 支持。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便