Flow of events

JavaScript manipulation of CSS is called scripted CSS, and JavaScript interacts with HTML through events. Events are specific moments of interaction that occur in a document or browser window, and event flow (also known as event propagation) describes the order in which events are received from the page.

history

As the browser progressed to its fourth generation (IE4 and Netscape4), the browser development team faced an interesting question: which part of the page would have a particular event? Imagine a set of concentric circles drawn on a piece of paper. If you place your finger on the center of a circle, it does not point to one circle, but to all the circles on the paper

The browser development teams of the two companies still see browser events in the same light. If a button is clicked, they all assume that the click occurred not only on the button, but also on the entire page **

Interestingly, the IE and Netscape development teams came up with almost the opposite concept of event flow. IE’s event flow is an event bubbling flow, while Netscape’s event flow is an event capture flow

The event bubbling

IE’s stream of events is called eventy bubbling, where an event is initially received by the most specific element (the node in the document with the deepest nesting) and then propagated up the hierarchy to the less specific node (the document)

Take the following HTML structure as an example to illustrate event bubbling, event capturing, and event flow

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#box{
				width: 200px;
				height: 200px;
				background-color: red;
			}
		</style>
	</head>
	<body>
		<div id="box">
			
		</div>
		<script type="text/javascript">
			var box = document.getElementById('box');
			box.onclick = function(){
				box.innerHTML += 'div\n';
			}
			document.body.onclick = function(){
				box.innerHTML += 'body\n';
			}
			document.documentElement.onclick = function(){
				box.innerHTML += 'html\n';
			}
			document.onclick = function(){
				box.innerHTML += 'body\n';
			}
			window.onclick = function(){
				box.innerHTML += 'window\n';
			}
		</script>
	</body>
</html>

Copy the code

If the

element in the page is clicked, the click event propagates up the DOM tree, occurring at each level of the node, in the following order:

Note: All modern browsers support bubbling, but there are some differences in implementation. IE9 +, Firfox, Chrome, and Safari bubble events all the way to the Window object

Event capture

The idea of event capture is that less specific nodes should receive events earlier, while the most specific nodes should receive events last. The intent of event capture is to catch an event before it reaches its intended destination

Take the same HTML structure as an example to illustrate event capture

During event capture, the Document object first receives the Click event, which then propagates down the DOM tree until it reaches the actual target of the event, the

element

Note: Modern browsers like IE9, Firefox, Chrome, and Safari support event capture, but start fetching from the Window object

AddEventListener (eventType, eventListener useCapture) method of the third parameter is set to true, when is the event capture phase

Flow of events

Event flow is also known as event propagation. The event flow defined by DOM2 events includes three phases: Capture Phase, Target Phase, and Bubbling Phase.

The first thing that happens is event capture, which provides an opportunity to intercept events. The actual target then receives the event, and the final stage is the bubbling stage, where it can respond to the event

Event handler

Event handlers, also called event listeners, are essentially event binding functions. The corresponding code in the function is executed when the event occurs. Event handlers:

  1. HTML event handler
  2. DOM0 level event handler
  3. Dom2-level event handler
  4. IE event handler

This section is described in more detail below

HTML event handler

Each event supported by an element can be specified using an HTML feature with the same name as the corresponding event handler. The value of this feature should be javascript code that can be executed

Inside the event handler function, this is equal to the target element of the event

<div id="box" style="height:30px; width:200px; background-color:pink;" onclick = "this.innerHTML+= '1';"></div>
Copy the code

Event handlers defined in HTML can also invoke scripts defined elsewhere on the page

<div id="box" style="height:30px; width:200px; background-color:pink;" onclick = "test()"></div>
<script>
    function test(){document.getElementById('box').innerHTML+= '1'; }</script>
Copy the code

The HTML event handler creates a function that encapsulates the value of an element’s attribute. This function has a local variable event, which is the event object. With the Event variable, you can access the event object directly without defining it yourself or retrieving it from the function’s argument list. (The next section focuses on properties on event objects.)

<div id="box" style="height:30px; width:200px; background-color:pink;"onclick = "this.innerHTML+= event.type;"></div>
Copy the code

Within event handler functions, document and members of the element itself can be accessed as if they were local variables. This makes it much easier for event handlers to access their own properties

<button id="box" value="test" style="height:30px; width:200px; background-color:pink;"onclick = "this.innerHTML+= value;"></button>
Copy the code
disadvantages

The coupling problem

The general style of client-side programming is to keep HTML content and javaScript behavior separate, so you should avoid using HTML event handler attributes, which directly mix javaScript and HTML and are not easily extensible

DOM0 level event handler

The traditional way to specify event handlers in javascript is to assign a function to an event handler property. This method of assigning values to event handlers was introduced in the fourth generation of Web browsers and is still supported by all modern browsers today. One is simplicity, and two is cross-browser advantage

Each element has its own event handler attributes, which are usually all lowercase, and you can specify an event handler by setting the value of this attribute to a function

Note: Event handlers added at the DOM0 level are processed during the bubbling phase of the event flow

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
document.getElementById('box').onclick = function(){this.innerHTML += '1'; }</script>    
Copy the code

An event handler can be removed by setting the event handler property to NULL

box.onclick = null;
Copy the code
disadvantages

Only one event handler can be added for each event type around each event target

Dom2-level event handler

The DOM2-level event handler defines two methods to handle specifying and removing event handlers: addEventListener() and removeEventListener().

Both methods are contained in all DOM nodes, and they each take three parameters: the name of the event to process, the function that acts as the event handler, and a Boolean value. The final Boolean argument, if true, calls the event handler during the capture phase; If false, the event handler is invoked during the bubbling phase. If the last Boolean value is left blank, it has the same effect as false

Note: Internet Explorer 8 does not support DOM2-level event handlers

The advantage of using DOM2-level event handlers is that multiple event handlers can be added and fired in the order in which they were added

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
	box.addEventListener('click'.function(){this.innerHTML += '1'},false);
	box.addEventListener('click'.function(){this.innerHTML += '2'},false);    
</script>    
Copy the code

The output result is: 12

To verify this, do a delay operation:

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    setTimeout(function(){
        box.addEventListener('click'.function(){this.innerHTML += '1'},false);    
    },10);
    box.addEventListener('click'.function(){this.innerHTML += '2'},false);    
</script>
Copy the code

The output is: 21

parameter

If you want to pass arguments to a listener function, you can wrap a listener function in an anonymous function

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.addEventListener("click".function(){
        test('123');
    },false);
    function test(x){box.innerHTML += x; }</script>
Copy the code
remove

Event handlers added via addEventListener() can only be removed using removeEventListener(), passing in the same parameters as when adding the handler. This means that anonymous functions added by addEventListener() cannot be removed.

The following is invalid

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.addEventListener("click".function(){
        this.innerHTML += '1'
    },false);
    box.removeEventListener('click'.function(){
        this.innerHTML += '1'
    },false);    
</script>
Copy the code

The following effective

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
    var handle = function(){this.innerHTML += '1'};
    box.addEventListener("click",handle,false);
    box.removeEventListener('click',handle,false);    
</script>
Copy the code

IE event handler

IE implements two methods similar to those in the DOM: attachEvent() and detachEvent(). Both methods take the same two parameters: the event handler name and the event handler function. Since IE8- only supports event bubbling, event handlers added through attachEvent() are added to the event bubbling phase

The first argument to the attachEvent() method is “onclick” instead of “click” in DOM’s addEventListener() method.

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.attachEvent('onclick'.function(){this.innerHTML += '1'; });</script>
Copy the code

Note: The attachEvent() method only bubbles to document and is supported by IE10

this

Unlike the other three event handlers, the IE event handler’s this refers to the window, not the element to which the event is bound.

<! --<div>-->
<div id="box" style="height:100px; width:300px; background-color:pink;"
onclick = "console.log(this)"></div>
Copy the code
<div id="box" style="height:100px; width:300px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.onclick= function(){
        console.log(this);//<div>
    }
</script>
Copy the code
<div id="box" style="height:100px; width:300px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.addEventListener('click'.function(){
        console.log(this);//<div>
    });
</script>
Copy the code
<div id="box" style="height:100px; width:300px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.attachEvent('onclick'.function(){
        console.log(this);//window
    });
</script>

Copy the code
The order

Event handlers added using the attachEvent() method fire in a different order. IE9 and ie10 execute in positive order, while IE8- executes in reverse order

<div id="box" style="height:30px; width:100px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.attachEvent('onclick'.function(){
        box.innerHTML += '1';
    });
    box.attachEvent('onclick'.function(){
        box.innerHTML += '2';
    });
</script>
Copy the code
remove

Events added using attachEvent() can be removed using detachEvent(), provided that the same arguments are provided. As with DOM methods, this means that added anonymous functions cannot be removed. However, as long as you can pass a reference to the same function to detachEvent(), you can remove the corresponding event handler

The following is invalid

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
    var box = document.getElementById('box');
    box.attachEvent("onclick".function(){
        box.innerHTML += '1'
    },false);
    box.detachEvent('onclick'.function(){
        box.innerHTML += '1'
    },false);    
</script>
Copy the code

The following effective

<div id="box" style="height:30px; width:200px; background-color:pink;"></div>
<script>
var handle = function(){box.innerHTML += '1'};
box.attachEvent("onclick",handle,false);
box.detachEvent('onclick',handle,false);    
Copy the code

conclusion

Since IE8- does not support the addEventListener() method, you need to work with the attachEvent() method to implement a browser-wide event-binding compatible writing method. Also, because this in the attachEvent() method points to the window, you need to explicitly change this.

function addEvent(target,type,handler){
    if(target.addEventListener){
        target.addEventListener(type,handler,false);
    }else{
        target.attachEvent('on'+type,function(event){
            returnhandler.call(target,event); }); }}Copy the code

Call to order

If all four event handlers are present in browsers at the same time, the order in which they are invoked is not consistent across browsers

<div id="box" style="height:100px; width:100px; background:pink;" onclick = "this.innerHTML +='html\n'"></div>
<script>
    var box = document.getElementById('box');
    if(box.addEventListener){
        box.addEventListener('click'.function(){this.innerHTML += 'level DOM2 \ n'})}if(box.attachEvent){
        box.attachEvent('onclick'.function(){box.innerHTML +='IE\n'})
    }
    box.onclick = function(){
        this.innerHTML += 'level DOM0 \ n';
    }
</script>
Copy the code

[Similarities]

If both an HTML event handler and a DOM0 level event handler are present, the DOM0 level overrides the HTML event handler

【 Difference 】

Chrome, Safari, FF, and Internet Explorer 11 result: DOM0 level DOM2 level

The result of Internet Explorer 9 and 10 is Dom0-level Internet Explorer 2

IE8- Browser result: DOM0 level IE

The event object

When an event on the DOM is triggered, an event object is generated, which contains all the information related to the event. All browsers support event objects, but in different ways. This article covers event objects in detail

Get event objects

  1. The event object is the first argument to the event handler

Note: Internet Explorer 8 is not supported

<! IE8- undefined, other browsers output object MouseEvent -->
<div id="box" style="height:30px; width:200px; background:pink;"></div>
<script>
var oBox = document.getElementById('box');
oBox.onclick = function(e){
    box.innerHTML = e;
}
Copy the code
  1. Another approach is to use the event variable directly

Firefox does not support it

<! -- Firefox outputs undefined, other browsers output object MouseEvent -->
<div id="box" style="height:30px; width:200px; background:pink;"></div>
<script>
var oBox = document.getElementById('box');
oBox.onclick = function(){
    box.innerHTML = event;
}
</script>
Copy the code
Compatible with

Thus, a common compatibility for getting event objects is written as follows

<div id="box" style="height:30px; width:200px; background:pink;"></div>
<script>
var oBox = document.getElementById('box');
oBox.onclick = function(e){
    e = e || event;
    box.innerHTML = e;
}
</script>
Copy the code

Click TAB to switch the focus to the button to start the focus event

<button id="box" style="height:30px; width:200px; background:pink;"></button>
<script>
var oBox = document.getElementById('box');
oBox.onfocus = function(e){
    e = e || event;
    box.innerHTML = e.type;
}
</script>
Copy the code

Event goals

For the event target, there are three attributes: currentTarget, Target, and srcElement

currentTarget

The currentTarget property returns the node where the event is currently located, that is, the node to which the executing listener is bound

Internet Explorer 8 does not support this function

The currentTarget property returns the node where the event is currently located, that is, the node to which the executing listener is bound

<style>
.in{height: 30px;background-color: lightblue;margin:0 10px; }</style>
<ul id="box">
    <li class="in">1</li>
    <li class="in">2</li>
</ul>
<script>
    var box = document.getElementById('box');
	box.onclick = function(e){
    e = e || event;
    var tags =  box.getElementsByTagName('li');
    tags[0].innerHTML = e.currentTarget;
    tags[1].innerHTML = (e.currentTarget === this);
}
</script>
Copy the code
target

The currentTarget attribute returns the node to which the listener is bound, while the target attribute returns the actual target node of the event

Internet Explorer 8 does not support this function

In the following code, the actual target node turns red when clicked; When removed, the color becomes light blue

<style>
    #box{background-color: lightblue; }.in{height: 30px; }</style>
<ul id="box">
    <li class="in">1</li>
    <li class="in">2</li>
</ul>
<script>
    box.onclick = function(e){
        e = e || event;
        e.target.style.backgroundColor = 'pink';
    }
    box.onmouseout = function(e){
        e = e || event;
        e.target.style.backgroundColor = 'lightblue';
    }
</script>
Copy the code
srcElement

The srcElement property has the same function as the target property

Note: Firefox is not supported

<style>
#box{background-color: lightblue; }.in{height: 30px; }</style>
<ul id="box">
    <li class="in">1</li>
    <li class="in">2</li>
</ul>
<script>
box.onclick = function(e){
    e = e || event;
    e.srcElement.style.backgroundColor = 'pink';
}
box.onmouseout = function(e){
    e = e || event;
    e.srcElement.style.backgroundColor = 'lightblue';
}
</script>

Copy the code
Compatible with
var handler = function(e){
    e = e || event;
    var target = e.target || e.srcElement;
}
Copy the code

The event agent

Since events propagate up to the parent node during the bubbling phase, you can define the listener function of the child node on the parent node and let the listener function of the parent node process events of multiple child elements uniformly. This approach is called delegation of events, or event delegation

The event broker completes this by applying the target and srcElement attributes of the event target. With event brokers, you can improve performance and reduce code complexity.

Take, for example, three colleagues who are expecting deliveries on Monday. In order to sign for the delivery, there are two ways: one is three people waiting for the delivery at the door of the company; Two is entrusted to the front MM to sign for. In reality, most of us use delegated solutions (and companies don’t tolerate so many employees standing at the door waiting for delivery). When the front desk MM receives the express, she will judge who the recipient is, and then sign for it according to the recipient’s requirements, or even pay for it. Another advantage of this scheme is that even if there is a new employee in the company (no matter how many), the receptionist will verify and sign for the new employee after receiving the package.

Requirement: there are 5 Li in one UL, turn blue when moving in, turn red when moving out

The following are implemented using the regular method and the event broker method respectively

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			ul {
				list-style: none;
			}
		</style>
	</head>
	<body>
		<ul id="box">
			<li>1</li>
			<li>2</li>
			<li>3</li>
			<li>4</li>
			<li>5</li>
		</ul>
		<script type="text/javascript">
			// 1. General method implementation

			/* var lis = document.getElementsByTagName('li'); for(var i = 0; i < lis.length; i ++){ lis[i].onmouseover = function (){ this.style.backgroundColor = 'blue'; } lis[i].onmouseout = function (){ this.style.backgroundColor = 'red'; }} * /
            // 2. Event proxy implementation
			ul.onmouseover = function(e) {
				e = e || event;
				var target = e.target || e.srcElement;
				target.style.backgroundColor = 'blue';
			}
			
			
		</script>
	</body>
</html>

Copy the code

Requirement: Add events to future elements

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			ul {
				list-style: none;
			}
		</style>
	</head>
	<body>
		<ul id="box">
			<li>1</li>
			<li>2</li>
			<li>3</li>
			<li>4</li>
			<li>5</li>
		</ul>
		<script type="text/javascript">
			
			// Add the corresponding data to simulate a future event
			var ul = document.getElementById('box');
			setTimeout(function(){
				
				var item = document.createElement('li');
				item.innerHTML = '6';
				ul.appendChild(item);
			},100)
			/ * / / 1. The primary way to add event Can not add elements of the event trigger future var lis = document. The getElementsByTagName (" li "); for(var i = 0; i < lis.length; i ++){ lis[i].onmouseover = function (){ this.style.backgroundColor = 'blue'; } lis[i].onmouseout = function (){ this.style.backgroundColor = 'red'; }} * /
			
			// 2. Event proxy implementation, can trigger future add element events
			ul.onmouseover = function(e) {
				e = e || event;
				var target = e.target || e.srcElement;
				target.style.backgroundColor = 'blue';
			}
			
		</script>
	</body>
</html>

Copy the code

The event bubbling

Event bubbling is the third phase of the event flow through which you can respond to events

Regarding bubbles, the event object contains four related properties and methods: bubbles, cancelBubble, stopPropagation() and StopatePropagation ().

bubbles

The bubbles property returns a Boolean value indicating whether the current event will bubble. This property is read-only

Most events that occur on document elements bubble, but focus, blur, and Scroll events do not. So, except for the three event bubbles properties that return false, the other events are all true

<button id="test" style="height: 30px; width: 200px;"></button>
<script>
    // When the button is clicked, the content of the button is true, meaning that the click event can bubble by default
    var test = document.getElementById('test');
    test.onclick = function(e){
        test.innerHTML =e.bubbles;//true
    }
</script>
Copy the code
<div id="box" style="height: 50px; width: 200px; overflow:scroll; background:pink; line-height:60px;">content</div>
<script>
    // When the div content is false, the Scroll event cannot bubble by default
    var box = document.getElementById('box');
    box.onscroll = function(e){
        test.innerHTML = e.bubbles;//false
    }
</script>
Copy the code
stopPropagation()

The stopPropagation() method represents further capture or bubbling of the cancel event, with no return

Note: Internet Explorer 8 is not supported

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button id="btn">The trigger</button>
		<script type="text/javascript">
			var btn = document.getElementById('btn');
			btn.onclick = function (e){
				e = e || event;
				e.stopPropagation();
				this.innerText = 'Stop bubbling';
			}
			document.body.onclick = function (e){
				alert('bubble');
			}
		</script>
	</body>
</html>

Copy the code
stopImmediatePropagation()

The stopImmediatePropagation() method can not only cancel further capture or bubble of an event, but also prevent other listener functions of the same event from being called, with no return value

[Note] Internet Explorer 8- not supported

Using the stopIPropagation() method, you can prevent bubbling, but you can’t prevent other listener functions of the same event from being called

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button id="btn" style="width: 200px;">The trigger</button>
		<script type="text/javascript">
			var btn = document.getElementById('btn');
			// Can prevent bubbling, but does not prevent other listener functions of the same event from being called
			btn.addEventListener('click'.function (e){
				e = e || event;
				e.stopPropagation()
				this.innerHTML = 'modified';
			})
			btn.addEventListener('click'.function (e){
				e = e || event;
				this.style.backgroundColor = 'lightblue';
			})
			document.body.addEventListener('click'.function (){
				alert('body');
			})
		</script>
	</body>
</html>

Copy the code

The stopImmediatePropagation() method was used to prevent bubblings and other listener functions from being called for the same event

<button id="btn" style="width: 200px;">The trigger</button>
<script type="text/javascript">
    var btn = document.getElementById('btn');
    // Can prevent bubbling, but does not prevent other listener functions of the same event from being called
    btn.addEventListener('click'.function (e){
        e = e || event;
        e.stopImmediatePropagation()
        this.innerHTML = 'modified';
    })
    btn.addEventListener('click'.function (e){
        e = e || event;
        this.style.backgroundColor = 'lightblue';
    })
    document.body.addEventListener('click'.function (){
        alert('body');
    })
</script>
Copy the code
cancelBubble

The canceBubble property can only be used to prevent bubbling, not the capture phase. This value is read-write and defaults to false. When set to true, cancelBubble cancels event bubbling

[Note] This property is supported by all browsers, but is not written as a standard

<button id="btn">The trigger</button>
<script type="text/javascript">
    var btn = document.getElementById('btn');
    btn.onclick = function (e){
        e = e || event;
        e.cancelBubble = true;
        this.innerText = 'Stop bubbling';
    }
    document.body.onclick = function (e){
        alert('bubble');
    }
</script>
Copy the code
Compatible with
var handler = function(e){
    e = e || event;
    if(e.stopPropagation){
        e.stopPropagation();
    }else{
        e.cancelBubble = true; }}Copy the code

Event flow stage

eventPhase

The eventPhase property returns an integer value that represents the current phase of the event flow that the event is in

0 indicates that the event did not occur, 1 indicates the capture phase, 2 indicates the target phase, and 3 indicates the bubbling phase

[Note] Internet Explorer 8- not supported

[1] The following code returns 2, indicating that it is in the target stage

<button id="btn">Flow of events</button>
<script type="text/javascript">
    var btn = document.getElementById('btn');
    btn.onclick = function (e){
        e =  e || event;
        this.innerHTML = e.eventPhase + 'stage';
    }
</script>
Copy the code

[2] The following code returns 1, indicating that it is in the capture phase

<button id="btn">Flow of events</button>
<script type="text/javascript">
    var btn = document.getElementById('btn');
    document.addEventListener('click'.function(e){
        e = e || event;
        btn.innerHTML += e.eventPhase +'stage';
    },true);
</script>
Copy the code

[3] The following code returns 3, indicating that it is bubbling

<button id="btn">Flow of events</button>
<script>
    document.addEventListener('click'.function(e){
        e = e || event;
        btn.innerHTML += e.eventPhase +'stage';
    },false);
</script>
Copy the code

Cancel default behavior

A common default behavior is to click a link and redirect the browser to a specified page. Or press the space bar to scroll down some distance

Properties to cancel the default behavior include preventDefault() and returnValue

use

1. Disable default behavior in DOM0 event handler with returnValue, preventDefault() and return False

Undo default behavior in DOM2 event handler. Return false is invalid

3, disable the default behavior in IE event handler, preventDefault() is invalid

Click on the following anchors to automatically open the little Ape circle home page

<a id="test" href="https://www.apeland.cn" target="_blank">Small circle ape</a>
Copy the code
preventDefault()

The preventDefault() method cancels the browser’s default behavior for the current event with no return value

Note: Internet Explorer 8 is not supported

<a id="test" href="http://www.cnblogs.com">link</a>
<script>
    var test = document.getElementById('test');
    test.onclick= function(e){
        e = e || event;
        e.preventDefault();
    }
</script>
Copy the code
returnValue

The returnValue property is read-write and the default is true, but setting it to false cancels the event’s default behavior, as the preventDefault() method does

Note: Firebox and IE9 are not supported

<a id="test" href="http://www.cnblogs.com">link</a>
<script>
    var test = document.getElementById('test');
    test.onclick= function(e){
        e = e || event;
        e.returnValue = false;
    }
</script>
Copy the code
Compatible with
var handler = function(e){
    e = e || event;
    if(e.preventDefault){
        e.preventDefault();
    }else{
        e.returnValue = false; }}Copy the code
return false

In addition to the above methods, you can also cancel the default event by using return false

<a id="test" href="http://www.cnblogs.com">link</a>
<script>
    var test = document.getElementById('test');
    test.onclick= function(e){
        return false;
    }
</script>
Copy the code

Event object properties

The mouse event object provides a wealth of information

coordinates

The event object provides clientX/Y, pageX/Y, screenX/Y, x/ Y, offsetX/Y, and layerX/Y pairs of coordinate positions

ClientX/Y and x/Y

ClientX /Y represents the X-axis and Y-axis position of the mouse relative to the browser (in this case, the browser’s valid area) when a mouse event occurs (whether onclick, omousemove, onmouseover, etc.); X/ y is the same as clientX/ y

<body>
    <div id="box" style="width: 200px; height: 200px; background-color: red;"></div>
    <script type="text/javascript">
        var box = document.getElementById('box');
        box.onmousemove = function(e){
            e = e || event;
            // Horizontal and vertical coordinates of the mouse pointer relative to the browser
            this.innerHTML = `clientX:${e.clientX}; clientY:${e.clientY}; clientY:${e.x}; clientY:${e.y}; `;
           
        }
    </script>
</body>
Copy the code
screenX/Y

When the mouse event occurs, the mouse relative to the display screen X-axis position and Y-axis distance;

<body>
    <div id="box" style="width: 200px; height: 200px; background-color: red;"></div>
    <script type="text/javascript">
        var box = document.getElementById('box');
        box.onmousemove = function(e){
            e = e || event;
            // The horizontal and vertical coordinates of the mouse pointer in the viewable area
            this.innerHTML = `screenX:${e.screenX},screenY:${e.screenY}`;
        }
    </script>
</body>
Copy the code
pageX/Y

PageX /Y represents horizontal and vertical coordinates relative to the page, which differs from clientX/clientY in that it varies with the position of the scroll bar

<body style="height: 2000px;">
    <div id="box" style="width: 200px; height: 200px; background-color: red;"></div>
    <div id="result"></div>
    <script type="text/javascript">
        var box = document.getElementById('box');
        var result = document.getElementById('result');

        box.onmousemove = function(e){
            e = e || event;
            result.innerHTML = `clientX:${e.clientX}; clientY:${e.clientY}<br>pageX:${e.pageX},pageY:${e.pageY}`;
        }
    </script>
</body>
Copy the code
OffsetX and offsetY

OffsetY: Indicates the position of the mouse relative to the Y-axis of the event source when the mouse event occurs

<body style="height: 2000px;">
    <div id="box" style="width: 200px; height: 200px; background-color: red;">
    </div>
    <div id="result"></div>
    <script type="text/javascript">
        var box = document.getElementById('box');
        var result = document.getElementById('result');
        box.onmousemove = function(e){
            e = e || event;
            this.innerHTML = `clientX:${e.clientX}; clientY:${e.clientY}; offsetX:${e.offsetX}; offsetY:${e.offsetY}; `;
        }
    </script>
</body>
Copy the code