Front-end Architect 11_JavaScript Events

1 event handling

1.1 Event Overview

Before learning about events, there are several important concepts to understand:

  • event
  • event handler
  • event driven
  • event stream
event

Can be understood as behavior detected by JavaScript.

These behaviors refer to page loading, mouse clicking on the page, mouse sliding over a certain area, etc.

event handler

It refers to the program code executed by JavaScript in response to user actions.

When the user clicks the button button, this behavior will be detected by the click event in JavaScript; then it will be automatically executed, and the program code written for the click event will be output to the console as "the button was clicked".

event driven

It refers to the process of JavaScript events in Web pages, detecting user behavior, and executing corresponding event handlers.

When the mouse moves into the text area, the text area changes color.

event stream

When an event occurs, it will be propagated in a specific order between the element node where the event occurred and the DOM tree root node. The process of event propagation is the event stream.

Netscape proposed the "event capturing method" and Microsoft proposed the "event bubbling method".

  • Event capture method (Netscape): The order of event stream propagation should be from the root node of the DOM tree to the element node where the event occurs.

  • Event bubbling method (Microsoft): The order of event stream propagation should be from the element node where the event occurs to the root node of the DOM tree.

W3C’s solution

  • It is stipulated that after the event occurs, the event capture is implemented first, but the event will not be processed.
  • Then proceeding to the target phase, the event handler of the current element object is executed, but it will be regarded as part of the bubbling phase.
  • Finally, the bubbling of events is realized and the events are processed step by step.

1.2 Binding method of events

Event binding refers to binding an event handler to an event of an element object.

  • Inline binding
  • Dynamic binding
  • event listening
Inline binding

Inline binding of events is achieved through attribute settings of HTML tags.

<标签名  事件="事件的处理程序">
  • The tag name can be any HTML tag, such as <div>tag, <button>tag, etc.;
  • The event is an HTML attribute composed of on and the event name. For example, the attribute corresponding to the click event is named onclick;
  • Event handlers refer to JavaScript code, such as anonymous functions, etc.

Because it is advocated to separate JavaScript code and HTML code during development. Therefore, it is not recommended to use inline binding events.

Dynamic binding

The problem of mixing JavaScript code and HTML code.

In the JavaScript code, add events and event handlers for the DOM element objects that require event processing.

DOM元素对象.事件 = 事件的处理程序;

Event handlers are generally anonymous functions or named functions.

Similarities and differences between inline binding and dynamic binding

difference:

  • The implementation syntax is different. The former is set through the attributes of HTML tags, and the latter handles DOM objects in JS.
  • The pointing of the keyword this in the event handler is also different. The former points to the window object, and the latter points to the DOM element object currently being operated on.

Same point:

  • There can only be one event handler for the same event on the same DOM object.
event listening

The same event of the same DOM object can only have one event handler. You can add multiple event handlers to the same event of the same DOM object.

There are two implementation methods, which have compatibility issues. One is early versions of IE browsers (such as IE6~8), and the other is browsers that follow W3C standards (hereinafter referred to as standard browsers).

// 早期版本的IE浏览器
DOM对象.attachEvent(type, callback);
  • The parameter type refers to the event type bound to the DOM object, which consists of on and the event name, such as onclick.
  • The parameter callback represents the event handler.
// 标准浏览器
DOM对象.addEventListener(type, callback, [capture]);
  • The parameter type refers to the event type bound to the DOM object, which is set by the event name, such as click.
  • The parameter callback represents the event handler.
  • The default value of the parameter capture is false, which means that event processing is completed in the bubbling stage. When it is set to true, it means that event processing is completed in the capturing stage.

The difference between two different implementation methods of event monitoring

  • The implemented syntax is different.
  • The triggering order of event handlers is also different. For the same event of the same object, the event handlers of earlier versions of IE browser are executed in reverse order of adding. The standard browser event handlers are executed in the order they were added.

When the event listener's handler is a named function, the event listener can be removed.

  • DOM object.detachEvent(type, callback); //Early version of IE browser
  • DOM object.removeEventListener(type, callback); // Standard browser

The setting of the parameter type value should be the same as the event type of the added event listener. The parameter callback represents the name of the event handler, that is, the function name.

2 event objects

2.1 Get event object

When an event occurs, an event object event is generated.

This object contains all event-related information, including the DOM element where the event occurred, the type of event, and other information related to a specific event.

For example, when an event occurs due to mouse movement, the event object will include related information such as the mouse position (horizontal and vertical coordinates);

How to get the event object

  • Early IE browsers (IE6~8): window.event
  • Standard browser: An event object will be passed directly into the event handler.
var event = e || window.event; 

2.2 Common properties and methods

After an event occurs, the event object event not only contains information related to the specific event, but also contains some properties and methods that are common to all events.

Classification Properties/Methods describe
public type Returns the type of current event, such as click
Standard browser event object target Returns the element that triggered this event (the target node of the event)
Standard browser event object currentTarget Returns the element whose event listener triggered the event
Standard browser event object bubbles Indicates whether the event is a bubbling event type
Standard browser event object cancelable Indicates whether the event cancels the default action
Standard browser event object eventPhase Returns the current stage of event propagation. 1 represents the capture stage, 2 represents the target stage, and 3 represents the bubbling stage.
Standard browser event object stopPropagation() Prevent events from bubbling up
Standard browser event object preventDefault() Block default behavior
Early version IE browser event object srcElement Returns the element that triggered this event (the target node of the event)
Early version IE browser event object cancelBubble Prevent events from bubbling. The default is false to allow, and setting true to prevent it.
Early version IE browser event object returnValue Block the default behavior, the default is true to allow, set false to block
var btn = document.getElementById('btn');
btn.onclick = function(e) {
    
    
    var obj = event.target || window.event.srcElement;
    console.log(obj.nodeName); 
    console.log(obj.id);
    console.log(obj.className); 
    console.log(obj.innerText); 
};
// 事件冒泡
red.onclick = function() {
    
     console.log('red'); };
green.onclick = function() {
    
     console.log('green'); };
yellow.onclick = function() {
    
     console.log('yellow'); };
// 阻止事件冒泡
if (window.event) {
    
    	// 早期IE浏览器
    window.event.cancelBubble = true;
} else {
    
    			// 标准浏览器
    e.stopPropagation();
}

Some element tags in HTML have special behaviors. For example, <a>after clicking the label, it will automatically jump to the URL link specified by the href attribute; after clicking the submit button of the form, the form data will automatically be submitted to the specified server-side page for processing. Therefore, we call this behavior of labels the default behavior.

<a id="test" href="http://www.example.com">默认链接</a>
<script>
    document.getElementById('test').onclick = function(e) {
      
      
        if (window.event) {
      
       // 早期版本IE浏览器
            window.event.returnValue = false;
        } else {
      
       //标准浏览器
            e.preventDefault();
        }
    };
</script>

2.3 Practice assignments

  • slow moving ball
    • Animation special effects: It is one of the common functions of JavaScript.
    • The implementation principle of easing: continuously modify a certain style value of the current DOM element through a timer to achieve a dynamic special effect.
    • Easing animation formula:
      • Calculate the step size of each easing step = (target - leader) / 10
      • Calculate the next starting point leader = leader + step
      • target represents the target point.
      • leader represents the starting point.
      • step represents the step size of each easing from the starting point to the target point. When the easing effect is implemented, as the distance from the target gets closer and closer, the step value gradually becomes smaller, thereby achieving a very realistic easing effect.
    • Use <div>to design the ball and use CSS to set the position of the ball.
    • Bind a click event to the ball, and call the custom animate() in the handler function to achieve easing of the ball.
    • Write the animate() animation function, use the timer in the function, and complete the easing animation according to the easing formula.

3 Event classification

3.1 Page events

In what order are HTML pages loaded?

The page is loaded from top to bottom in the order in which the code is written.

Problems that may occur: If JavaScript is used to operate DOM elements before the page is loaded, syntax errors will occur.

<!-- 页面加载顺序的问题-->
<script>
    document.getElementById('demo').onclick = function () {
      
      
        console.log('单击');
    };
</script>
<div id="demo"></div>

Solution: Page events can change the execution timing of JavaScript code.

  • load event: It is triggered after all tags in the body have been loaded. Since there is no need to consider the page loading order, it is often added when developing specific functions.
  • unload event: triggered when the page is closed, often used to clear references to avoid memory leaks.
window.onload = function() {
    
    
    // JavaScript代码
};

3.2 Focus event

In web development, focus events are mostly used for form validation functions and are one of the most commonly used events.

For example, changing the style of the text box when the text box gets focus, validating the data entered in the text box when the text box loses focus, etc.

event name Event trigger time
focus Triggered when focus is obtained (will not bubble)
blur Fires when focus is lost (will not bubble)

3.3 Mouse events

Mouse events are the most commonly used type of events in web development.

For example, switching the content displayed in the Tab bar when the mouse slides over; using the mouse to drag the status box to adjust its display position, etc. These common web page effects all use mouse events.

event name Event trigger time
click Fires when any mouse button is pressed and released
dblclick Triggered when the mouse is double-clicked
mouseover Triggered when mouse enters
mouseout Triggered when mouse leaves
change Triggered when the content changes, generally used for <select>objects
mousedown Fires when any mouse button is pressed
mouseup Fires when any mouse button is released
mousemove Fires continuously when the mouse moves within the element

In project development, some commonly used mouse attributes are often involved, which are used to obtain the current mouse position information.

Location attribute (read only) describe
clientX The mouse pointer is located at the horizontal coordinate (X-axis coordinate) of the visible area of ​​the current window on the browser page
clientY The mouse pointer is located at the vertical coordinate (Y-axis coordinate) of the visible area of ​​the current window on the browser page
pageX The mouse pointer is located at the horizontal coordinate of the document (X-axis coordinate), which is not compatible with IE6~8
pageY The mouse pointer is located at the vertical coordinate (Y-axis coordinate) of the document. IE6~8 is not compatible.
screenX The mouse pointer is located at the horizontal coordinate of the screen (X-axis coordinate)
screenY The mouse pointer is located at the vertical coordinate of the screen (Y-axis coordinate)

The pageX and pageY attributes are not compatible in IE6 8 browser. Therefore, compatibility with IE6 and 8 browsers is required during project development .

var pageX = event.pageX || event.clientX + document.documentElement.scrollLeft;
var pageY = event.pageY || event.clientY + document.documentElement.scrollTop;

The coordinates of the mouse in the document are equal to the coordinates of the mouse in the current window plus the length of the text rolled by the scroll bar.

3.4 Homework exercises

  • Mouse drag effects

    • The position of the box (left and top values) = the position of the mouse (left and top values) - the distance between the mouse and the box (left and top values) when the mouse is pressed.
    • Write HTML and design pop-up boxes to implement drag-and-drop effects.
    • Add the mousedown event and its handler to the drag bar.
    • Handle mouse movement events to implement mouse dragging effects.
    • Handle the event of releasing the mouse button so that the pop-up box will no longer move after the mouse button is released.

3.5 Keyboard events

Keyboard events refer to events that are triggered when the user uses the keyboard.

For example, the user presses the Esc key to close the opened status bar, and presses the Enter key to directly switch the cursor up and down, etc.

event name Event trigger time
keypress Triggered when a keyboard key (except non-character keys such as Shift, Fn, CapsLock, etc.) is pressed
keydown Fires when a keyboard key is pressed
keyup Triggered when a keyboard key pops up

The key value saved by the keypress event is the ASCII code, and the key value saved by the keydown and keyup events is the virtual key code.

3.6 Form events

Form events refer to events that occur when operating a web form.

For example, verification of the form before submission, confirmation operation when the form is reset, etc. JavaScript provides related form events.

event name Event trigger time
submit Fires when form is submitted
reset 当表单重置时触发

4 练习作业

  • 图片放大特效
    • 准备两张相同的图片,小图和大图。
    • 小图显示在商品的展示区域。
    • 大图用于鼠标在小图上移动时,按比例的显示大图中的对应区域。
    • 编写HTML页面,展示小图、隐藏鼠标的遮罩及大图。
    • 当鼠标在小图上移动时,显示鼠标的遮罩和大图。
    • 当鼠标移动时,让遮罩跟着在小图中进行移动。
    • 限定遮罩在小图中的可移动范围。
    • 根据遮罩在小图中的覆盖范围,按比例的显示大图。

的确认操作等。JavaScript提供了相关的表单事件。

事件名称 事件触发时机
submit 当表单提交时触发
reset 当表单重置时触发

4 练习作业

  • 图片放大特效
    • 准备两张相同的图片,小图和大图。
    • 小图显示在商品的展示区域。
    • 大图用于鼠标在小图上移动时,按比例的显示大图中的对应区域。
    • 编写HTML页面,展示小图、隐藏鼠标的遮罩及大图。
    • 当鼠标在小图上移动时,显示鼠标的遮罩和大图。
    • 当鼠标移动时,让遮罩跟着在小图中进行移动。
    • 限定遮罩在小图中的可移动范围。
    • 根据遮罩在小图中的覆盖范围,按比例的显示大图。

Guess you like

Origin blog.csdn.net/zhangchen124/article/details/133351743