捕获JavaScript事件

As it loads and is read, every web page fires a cascade of events in JavaScript, with even more fired if the user interacts with the page in any way. A browser loading a page or being scrolled is an event; so to is clicking on a button or filling out a form element. Any event that is “fired” in JavaScript can trigger code that you design and write to create deeper interactivity.

在加载和读取页面时,每个网页都会触发JavaScript中的一系列事件,如果用户以任何方式与该页面进行交互,则还会触发更多事件。 浏览器加载页面或滚动是一个事件; 所以要单击一个按钮或填写一个表单元素。 JavaScript中“激发”的任何事件都可以触发您设计和编写的代码,以创建更深层次的交互性。

JavaScript events can be divided into four broad groups:

JavaScript事件可分为四大类:

  1. UI Events: occur when a user interacts with the browser UI - the i.e. the controls surrounding the page that are part of the browser, rather than the web page itself, or actions that the page takes independent of the user. Includes events such as the user resizing or scrolling the browser window, or the web page loading or unloading content.

    UI事件 :当用户与浏览器UI交互时发生-即,页面周围的控件是浏览器的一部分,而不是网页本身,或者该页面独立于用户执行的操作 。 包括事件,例如用户调整浏览器窗口大小或滚动浏览器,或网页加载或卸载内容。

  2. Keyboard, mouse and touch events: occur when the user presses or releases a key on the keyboard, or uses the mouse, trackpad, or touchscreen.

    键盘,鼠标和触摸事件 :当用户按下或释放键盘上的键,或使用鼠标,触控板或触摸屏时发生。

  3. Focus and form events. Most commonly associated with forms: an <input> “gains focus” when the user is prepared to interact with it; other events track the submission of a form, changing a value in a form field, etc

    集中并形成事件 。 最常见的形式是<input>当用户准备与之交互时“获得焦点”; 其他事件跟踪表单的提交,更改表单字段中的值等

  4. Mutation events and observers. Mutators track when the DOM is altered: for example, when elements are inserted or removed from a page with a script.

    突变事件和观察者 。 更改器跟踪DOM的更改时间:例如,何时使用脚本从页面中插入元素或从页面中删除元素

捆绑 (Binding)

Creating code that responds to a particular event on a chosen DOM element - known as “binding” an event to the element - creates an event handler. There are three ways to create event handlers in JavaScript:

创建对所选DOM元素上的特定事件做出响应的代码(称为“绑定”该元素的事件)会创建一个事件处理程序 。 使用JavaScript创建事件处理程序的方法有以下三种:

  1. Traditional HTML Event Handler via Attributes

    通过属性的传统HTML事件处理程序

    The oldest method of binding events, and one that you’ll still see used in a lot of code; uses specialized attributes inside markup. For example:

    绑定事件的最古老的方法,您仍然会在许多代码中看到这种方法。 在标记内使用专门的属性 。 例如:

    <input type="text" id="username" onblur="checkName()">

    In the example above, after the input has been selected and the user moves on (for example, pressing the TAB key or clicking in another input), the element will call the checkName function written in your JavaScript.

    在上面的示例中,选择了输入并且用户继续checkName (例如,按TAB键或单击另一个输入)之后,该元素将调用用JavaScript编写的checkName 函数

    Traditional HTML event handers are no longer recommended for modern development, primarily because it places functionality in the same place as markup, making it much harder to maintain and debug your code.

    不再推荐将传统HTML事件处理程序用于现代开发,这主要是因为它将功能标记放置在同一位置,这使得维护和调试代码变得更加困难。

  2. Traditional DOM Event Handlers

    传统DOM事件处理程序

    This technique separates JavaScript from your markup, but has the same limitation that events can only be associated with a single function. The equivalent to the HTML event handler above, written as a DOM event handler in a script, would be:

    该技术将JavaScript与标记分开,但具有相同的限制,即事件只能与单个函数关联。 与上面HTML事件处理程序等效,在脚本中被编写为DOM事件处理程序,将是:

    var username = document.getElementbyId("username");
    username.onblur = checkName;

    As before, removing focus from the form element would cause the function checkName to be run.

    和以前一样,从form元素上移开焦点将导致运行checkName函数。

  3. Event Listeners

    事件监听器

    The modern method of adding an event handler; allows multiple events and functions.

    添加事件处理程序的现代方法; 允许多个事件和功能。

    var username = document.getElementbyId("username");
    username.addEventListener("blur", checkName, false);

    The boolean at the end indicates if events should be captured; it is usually set to false.

    末尾的布尔值指示是否应捕获事件; 通常设置为false

    The triggered action is often written as an “anonymous” function in simple scripts:

    触发的操作通常用简单的脚本编写为“匿名”函数:

    var username = document.getElementbyId("username");
    username.addEventListener("blur", function() {
        // actions taken when the event is triggered
    })

Note that HTML and DOM Event handlers are prefixed with on, while event listeners are not.

请注意,HTML和DOM事件处理程序以on为前缀,而事件侦听器则没有。

I’ll be covering events in far greater detail in future articles; for now, there are a few things to note:

我将在以后的文章中更详细地介绍事件。 目前,有几件事要注意:

并非所有事件都是平等的 (Not All Events Are Equal)

It’s important to understand that not all events can be handled in the same way: some events, like scroll and resize, are fired multiple times during the event, and need to be treated carefully if you want your script to be efficient. This is also true with events that may appear inncuous at first, like input. Scripts can start to stagger and perform poorly as they attempt respond to the frequently-fired input events of elements like the range slider.

重要的是要理解并非所有事件都可以用相同的方式处理:某些事件(例如: scrollresize 在事件期间会被多次触发,如果您想使脚本高效,则需要谨慎对待。 对于最初可能看起来不连续的事件(例如input )也是如此。 脚本尝试响应range滑块之类的元素频繁触发的输入事件时,它们可能开始错开并表现不佳。

并非每个事件都被跟踪 (Not Every Event is Tracked)

Mutation observers do not currently track every alteration to every element: for example, there’s no set method for determining that the height of an element has changed (for example, as a container element narrows in a responsive design, reflowing the text inside it and causing the element to be longer). There are methods around this, however, as I’ll show in the next article.

突变观察者目前无法跟踪对每个元素的所有更改:例如,没有确定元素高度已更改的固定方法(例如,由于容器元素在响应式设计中变窄,将其内部的文本重排并导致元素要更长)。 但是,有解决方法,正如我将在下一篇文章中介绍的那样。

将事件附加到适当的元素 (Attach Events to Appropriate Elements)

The existence of events like onclick makes them tempting to apply to many elements, including links. As a general rule, links should remain free from JavaScript: if you click on a link, it should go to another area of the site, or to a new anchor point. On the other hand, if you want a UI element to change something on the same page, it should usually be a <button>, to which JavaScript can be applied with equanimity.

诸如onclick之类的事件的存在使它们很容易将其应用于许多元素,包括links 。 通常, 链接应不受JavaScript约束 :如果单击链接,则链接应转到网站的另一个区域或新的锚点 。 另一方面,如果您希望UI元素在同一页面上更改某些内容 ,则通常应为<button> ,可以轻松应用JavaScript。

CSS可以使用时不要使用JavaScript事件 (Don’t Use JavaScript Events when CSS Will Do)

JavaScript is slow and fragile compared to ; in general, CSS should be used whenever possible as an alternative to complex scripts. However, CSS has a limited range of interactivity: it does very well with :hover (which also covers touch events in many circumstances), and can cover click in some cases with :target. CSS animations will also automatically run on load, and there are CSS states that you can trigger based on elements like radio buttons, but anything more complex is usually best left to JavaScript.

相比,JavaScript缓慢且脆弱; 通常,应尽可能使用CSS代替复杂脚本。 但是,CSS的交互性范围有限:它与:hover配合得很好(在许多情况下它还涵盖了触摸事件),并且在某些情况下, 可以通过:target 来覆盖clickCSS动画也将在load自动运行,并且您可以根据单选按钮等元素触发CSS状态,但是通常最好让JavaScript处理任何复杂的事情。

翻译自: https://thenewcode.com/1109/Capturing-JavaScript-Events

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值