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:
我將在本文中解釋以下主題:
The document and window objects, and adding Event Listeners to them.
文檔和窗口對象,并向其中添加事件監聽器 。
The Event.preventDefault() method and it’s usage.
Event.preventDefault()方法及其用法。
The Event.stopPropagation() method with an example.
帶示例的Event.stopPropagation()方法。
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).
clientX和clientY :相對于內容區域(視口)左上方的位置。 只需單擊您的位置來分析這些屬性的值,就可以看到它們之間的關系。 即使向下滾動頁面,這些屬性也保持不變。 屏幕左上方(監視)的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 elementlink.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事件。 您想要實現以下用例:
- 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). 如果右鍵單擊該按鈕,則它應表明它已被單擊,并且不會傳播到父元素(即該段落)。
- 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 logicdocument.getElementById("button12").addEventListener("mousedown", function(event) {alert("button clicked");if (event.button == 2) // Right Clickevent.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/