如何处理JavaScript中的事件处理(示例和全部)

In this blog, I will try to make clear the fundamentals of the event handling mechanism in JavaScript, without the help of any external library like Jquery/React/Vue.

在此博客中,我将尝试在没有任何外部库(例如Jquery / React / Vue)的帮助下阐明JavaScript中事件处理机制的基础。

I will be explaining the following topics in this article:

我将在本文中解释以下主题:

  1. The document and window objects, and adding Event Listeners to them.

    文档窗口对象,并向其中添加事件监听器

  2. The Event.preventDefault() method and it’s usage.

    Event.preventDefault()方法及其用法。

  3. The Event.stopPropagation() method with an example.

    带示例的Event.stopPropagation()方法。

  4. How to remove an event listener from an element.

    如何从元素中删除事件侦听器。

具有事件监听器的 文档窗口对象 (Document and window objects with Event Listeners)

The Window object represents the tab. In case you are reading this blog on your corresponding browser, then your current tab represents the Window object.

Window对象代表选项卡。 如果您正在相应的浏览器上阅读此博客,则当前的选项卡表示Window对象。

The window object has access to such information as the toolbar, height and width of the window, prompts, and alerts. Let’s see how we can add an event listener (mousedown) to the window object and analyze some of its properties.

窗口对象可以访问诸如工具栏,窗口的高度和宽度,提示和警报之类的信息。 让我们看看如何向窗口对象添加事件监听器(mousedown)并分析其某些属性。

如何在窗口对象上添加侦听器 (How to add the listener on the window object)

The addEventListener method is the most preferred way to add an event listener to window, document or any other element in the DOM.

addEventListener方法是将事件侦听器添加到window文档或DOM中任何其他元素的最优选方法。

There is one more way called “on” property onclick, onmouseover, and so on. But is not as useful, as it does not allow us to add multiple event listeners on the same element. The other methods allow it.

还有另一种称为“ on”属性的方法,例如onclick,onmouseover等。 但是它没有用,因为它不允许我们在同一元素上添加多个事件侦听器。 其他方法允许它。

An event object is passed as an argument (optional) to the handler which contains all the information related to the event (in our case, mousedown) on the window.

事件对象作为参数(可选)传递给处理程序,该处理程序包含窗口上与事件相关的所有信息(在我们的情况下为mousedown)。

Open the developer tools (Inspect Element) on this page and copy paste the following code in the console panel and hit enter.

打开此页面上的开发人员工具(检查元素),然后将以下代码复制粘贴到控制台面板中,然后按Enter。

window.addEventListener("mousedown",function(event){
 alert("window");
 console.log(event);
});

After that, you can go over to any section of the current tab and right click to see the console and the info related to this event, as shown below in the snapshot.

之后,您可以转到当前选项卡的任何部分,然后右键单击以查看控制台和与此事件相关的信息,如下快照所示。

Note: If you go to any other tab and right click, then this event will not get fired as it belongs to this tab (Window object) only.

注意 :如果转到任何其他选项卡并单击鼠标右键,则不会触发此事件,因为该事件仅属于此选项卡(Window对象)。

mousedown事件的详细信息 (The details of the mousedown event)

In the next few lines, I will explain some of the important captured property corresponding to the mousedown event we just performed.

在接下来的几行中,我将解释一些与我们刚刚执行的mousedown事件相对应的重要捕获属性。

button: As this was the mousedown event, it will tell you the button you clicked. For the mouse, Left, middle, and right correspond to 0, 1, and 2 respectively. If you click the right button, you can see the value 2.

button :由于这是mousedown事件,它将告诉您单击的按钮。 对于鼠标,左,中和右分别对应于0、1和2。 如果单击右键,则可以看到值2。

clientX and clientY: Position relative to the upper left of the content area (Viewport). Just analyze the value of these properties with the place you clicked, and you can see how they’re related. Even if you scroll down the page, these properties remain the same. ScreenX and ScreenY reference from the top left of the screen (Monitor).

clientXclientY :相对于内容区域(视口)左上方的位置。 只需单击您的位置来分析这些属性的值,就可以看到它们之间的关系。 即使向下滚动页面,这些属性也保持不变。 屏幕左上方(监视)的ScreenX和ScreenY参考。

altkey / ctrlkey: If you keep any of these keys pressed while performing your right click operation, then you can see these values are true. Otherwise, they’re false as in our case.

altkey / ctrlkey :如果在执行右键单击操作时按住这些键中的任何一个,则可以看到这些值是正确的。 否则,它们与我们的情况一样是错误的。

target: It corresponds to the element you performed the action upon. Whatever element you might have clicked on, you can see the information corresponding to this property in the console

目标:它对应于您对其执行操作的元素。 无论您单击什么元素,都可以在控制台中看到与此属性对应的信息

什么是文档对象(What is a document object?)

The document consists of what is inside the inner window. The document object is the root of every node in the DOM. If you are loading an HTML page in the browser, then the document represents that entire page.

该文档由内部窗口中的内容组成。 文档 对象是DOM中每个节点的根。 如果要在浏览器中加载HTML页面,则文档代表整个页面。

Event.preventDefault()方法及其用法 (The Event.preventDefault() method and its usage)

Sometime we don’t want an HTML element to behave in the way it is supposed to behave in default. In such a case, we can use this method.

有时候,我们不希望HTML元素的行为与默认情况下的行为相同。 在这种情况下,我们可以使用这种方法。

Example: Clicking the anchor element will make the browser redirect to that page by default. Let’s try to avoid that.

示例 :单击锚点元素将使浏览器默认情况下重定向到该页面。 让我们尝试避免这种情况。

<html>

<body>

  <a href="https://google.com/">Google</a>

  <script>
    let link = document.querySelector("a"); // It is the method to access the first matched element
    link.addEventListener("click", function(event) {
      console.log("Redirecting Stopped");
      event.preventDefault();
    });
  </script>
</body>

</html>

You can create an HTML file and check out this code.

您可以创建一个HTML文件并签出此代码。

Event.stopPropagation()方法 (The Event.stopPropagation() method)

Events flow outwards. There are certain cases, such as when you have nested elements and you perform some event on a child and it ends up performing some action on the parent, too, that you want to avoid. In such cases, this method is a useful one.

事件向外流动。 在某些情况下,例如,当您具有嵌套元素并在子级上执行某些事件而最终在父级上执行某些操作时,也要避免这种情况。 在这种情况下,此方法是一种有用的方法。

It sounds bit confusing, but I hope the below example will make it clear to you.

这听起来有点令人困惑,但是我希望下面的例子能使您清楚。

Imagine you have a button inside a paragraph and you have attached a mousedown event to both of them. You want to achieve the following use cases:

想象一下,您在一个段落中有一个按钮,并且对它们两个都附加了mousedown事件。 您想要实现以下用例:

  1. If you right click the button, then it should show that it has been clicked and does not propagate to the parent element (that is, the paragraph).

    如果右键单击该按钮,则它应表明它已被单击,并且不会传播到父元素(即该段落)。
  2. If you left click on the button, then it should propagate outwards normally and fire the paragraph event listener, too.

    如果左键单击该按钮,则它应正常向外传播并触发段落事件侦听器。

Solution:

解:

<html>

<body>
  <p id="demo"> Hello Ho<button id="button12"> Button2 </button> </p>
  <script>
    // Event Listener on the Button and it's logic
    document.getElementById("button12").addEventListener("mousedown", function(event) {
      alert("button clicked");
      if (event.button == 2) // Right Click
        event.stopPropagation();
    });
    // Event Listener on the paragraph element with it's logic:
    document.getElementById("demo").addEventListener("mousedown", function(event) {
      alert("Paragraph clicked");
    });
  </script>
</body>

</html>

从元素中删除 事件监听(Removing an event listener from an element)

In order to remove an event listener from an element, we need to call the removeEventListener method with the event name and the function name.

为了从元素中删除事件侦听器,我们需要使用事件名称和函数名称调用removeEventListener方法。

Note: when anonymous functions are passed, they don’t have memory mapping. So we need to define those functions outside the callback and then reference them here in the removeEventListener callback.

注意 :传递匿名函数时,它们没有内存映射。 因此,我们需要在回调之外定义这些函数,然后在removeEventListener回调中在此处引用它们。

Document.getElementbyId("id_name").removeEventListener("click",fn_name)

If you have reached this point, you should have a decent understanding of how Event Listeners work in the JavaScript.

如果您已经达到了这一点,那么您应该对事件监听器在JavaScript中的工作方式有一个不错的了解。

If, while working with your favorite library/Frameworks, you ever get stuck in the Events Handling part, then these basics should help you to resolve the issue.

如果在使用您喜欢的库/ Framework时遇到“事件处理”部分的困扰,那么这些基础知识应该可以帮助您解决问题。

翻译自: https://www.freecodecamp.org/news/event-handling-in-javascript-with-examples-f6bc1e2fff57/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值