The event

  • Note: Event methods are not humped
  • == The mobile terminal and the PC terminal have unique events ==
  • CSS pointerevents: none; Pointerevents: None; pointerEvents: None; Can cause the dom selected by the corresponding selector to not respond to do not intercept events

Move in, move out, Move (Move terminal has no move in, move out event)

  • .onmouseover .onmouseenter
  • .onmouseout .onmouseleave
  • .onmousemove
  • Dubious! No hump
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>13-JavaScript- Move in and move out events</title>
    <style>* {margin: 0;
            padding: 0;
        }
        div{
            width: 300px;
            height: 300px;
            background: red;
        }
    </style>
</head>
<body>
<div></div>
<script>
    let oDiv = document.querySelector("div");
    // 1. Move the event
    // oDiv.onmouseover = function () {
    // console.log(" move in event ");
    // }
    Note: For starters, onmouseEnter is recommended to avoid unknown bugs
    oDiv.onmouseenter = function () {
        console.log("Migration event");
    }

    // 2. Remove the event
    // oDiv.onmouseout = function () {
    // console.log(" remove event ");
    // }
    // Note: For beginners, onmouseleave is recommended to avoid unknown bugs
    oDiv.onmouseleave = function () {
        console.log("Removal event");
    }
    3.Move event odiv.onMousemove =function () {
        console.log("Moving event");
    }
</script>
</body>
</html>
Copy the code

Form-focused events

  • .onfocus
  • .onblur
  • .onchange (You can only get the modified data after losing focus)
  • .onINPUT (Get modified data in real time)
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>17-JavaScript- Focus events</title>
</head>
<body>
<input type="text">
<script>
    let oInput = document.querySelector("input");
    // 1. Listen for input to get focus
    oInput.onfocus = function () {
        console.log("Got the focus.");
    }
    // 2. Listen for input to lose focus
    oInput.onblur = function () {
        console.log("Lost focus.");
    }
    // 3. Listen for input changes
    // Note: the onchange event can only get the modified data if the form loses focus
    oInput.onchange = function () {
        console.log(this.value);
    }
    // The oninput event can always get the data after the user changes, whenever the user changes the data will call (execute)
    // Note: the onInput event can only be used in Internet Explorer 9 or later
    // Under IE9, if you want to obtain the modified data from time to time, you can use the onPropertyChange event to achieve this
    oInput.oninput = function () {
        console.log(this.value);
    }
</script>
</body>
</html>
Copy the code

Three ways to add events

  1. element.onxxx
  2. Element. AttachEvent
  3. Element.addeventlistener (modern, optional event bubbling or capture)

Method 1: onxxx

Note:

  1. Since the attribute is assigned, the last assignment overrides the previous assignment
  2. The disadvantage is obvious: you can’t fire multiple methods through a single event, which is not conducive to maintaining the granularity of methods
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>onclick</title>
</head>
<body>
<button id="btn">I am a button</button>
<script>
    // The click event will only output 777. The principle is that reassigning an object property overwrites the original value
    var oBtn = document.getElementById("btn");

    oBtn.onclick = function () {
        alert("666");
    }
    oBtn.onclick = function () {
        alert("777");
    }
</script>
</body>
</html>
Copy the code

Method 2: attachEvent

Note:

  1. The event name must be preceded by on
  2. What is added later does not overwrite what was added first
  3. Only older browsers are supported
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>attachEvent</title>
</head>
<body>
<button id="btn">I am a button</button>
<script>
    // Outputs both 666 and 777, but modern browsers have abandoned this method
    var oBtn = document.getElementById("btn");

    oBtn.attachEvent("onclick".function () {
        alert("666");
    });
    oBtn.attachEvent("onclick".function () {
        alert("777");
    });
</script>
</body>
</html>
Copy the code

Method 3: addEventListen

Note:

  1. You do not need to add on to the event name
  2. What is added later does not overwrite what was added first
  3. Only supports modern browsers (which is perfectly sufficient)
  4. This is the only method of the three that allows you to customize whether an event is bubbling or trapping
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>addEventListener</title>
</head>
<body>
<button id="btn">I am a button</button>
<script>
    // Print both 666 and 777, which is common in modern browsers
    var oBtn = document.getElementById("btn");

    oBtn.addEventListener("click".function () {
        alert("666");
    });
    oBtn.addEventListener("click".function () {
        alert("777");
    });

</script>
</body>
</html>
Copy the code

Forced compatible

It looks thoughtful, but it’s not necessary

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add a judgment</title>
</head>
<body>
<button id="btn">I am a button</button>
<script>
    var oBtn = document.getElementById("btn");

    function addEvent(ele, name, fn) {
        if(ele.attachEvent){
            ele.attachEvent("on"+name, fn);
        }else{ ele.addEventListener(name, fn); }}</script>
</body>
</html>
Copy the code

The event object

  • An event object is an object automatically created by a system
  • When the registered event is triggered, the system automatically creates the event object
  • The properties of the event object are lost

Note:

  1. In advanced versions of browsers, event objects are automatically passed to the back function
  2. In lower versions of browsers, event objects are not automatically passed to the callback function and need to be retrieved via window.event

About blocking default behavior:

  1. event.preventDefault(); Only modern browsers are supported
  2. event.returnValue = false; Only supports ancient browser (understand can, these days who still use IE8 ah)
  3. return false; winner-take-all
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The event object</title>
</head>
<body>
<button id="btn">I am a button</button>
<a href="http://www.baidu.com">Baidu's home page</a>
<script>
   var oBtn = document.getElementById("btn");
   oBtn.onclick = function (event) {
       // Compatibility
       event = event || window.event;
       // alert("666");
       console.log(event);
       console.log(typeof event);
   }

   let oA = document.querySelector("a");
    oA.onclick = function (event) {
        // Compatibility
        event = event || window.event;

        alert("666");
        // Prevent default behavior
        return false; // Enterprise development recommendation

        // event.preventDefault(); // Advanced browser
        // event.returnValue = false; // Internet Explorer 9
    }
</script>
</body>
</html>
Copy the code

Three phases of event execution

The three stages

  1. Capture phase (passing events from outside in)
  2. Current target stage
  3. Bubbling phase (passing events from inside out)

Note:

  • Only two of the three phases will be executed simultaneously
  • Either catch and current or current and bubble

Why is it either catch and current or current and bubble?

This is the history of JS handling events

In the early days, there were two streams of capture and bubbling among major browser vendors for competing definitions and different understandings of events

Subsequently, the W3C included both methods in the standard for compatibility

Bubble or capture

How do I set whether an event is captured or bubbled?

With the addEventListener method, this method takes three parameters

  • The first parameter: the name of the event
  • The second argument: the callback function
  • Third argument: ==false bubble == / ==true capture ==

Note:

  • The onXxx property accepts no arguments, so bubbles by default
  • The attachEvent method can only accept two arguments, so the default is bubbling
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>41-JavaScript- Three stages of event execution</title>
    <style>* {margin: 0;
            padding: 0;
        }
        .father{
            width: 300px;
            height: 300px;
            background: red;
        }
        .son{
            width: 150px;
            height: 150px;
            background: blue;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son"></div>
</div>
<script>
    let oFDiv = document.querySelector(".father");
    let oSDiv = document.querySelector(".son");
    oFDiv.addEventListener("click".function () {
        console.log("father");
    }, false);
    oSDiv.addEventListener("click".function () {
        console.log("son");
    }, false);
</script>
</body>
</html>

<! The default is false, that is, the bubble set to true elements and their child chains are captured, and only affect themselves and their children, not their parents.
Copy the code

Details about bubbling

IE6.0: div -> body -> html -> document

Other browsers: div -> body -> HTML -> document -> window

Note: Not all events can bubble. Some events do not bubble, such as blur, focus, Load, unload, etc

Prevent event bubbling (forced compatibility)

First, make it clear that blocking requires an event, and the action to prevent event bubbling is written in the callback function of the practice method

  1. event.cancelBubble = true; (ancient times)
  2. event.stopProgagation(); (Modern, that’s important to know)
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>43-JavaScript- Prevents events from bubbling</title>
    <style>* {margin: 0;
            padding: 0;
        }
        .father{
            width: 300px;
            height: 300px;
            background: red;
        }
        .son{
            width: 150px;
            height: 150px;
            background: blue;
        }
    </style>
</head>
<body>
<div class="father" id="father">
    <div class="son" id="son"></div>
</div>
<script>
    // 1. Get the element to operate on
    var oFDiv = document.getElementById("father");
    var oSDiv = document.getElementById("son");
    
    // 2. Register event listeners
    oFDiv.onclick = function () {
        console.log("father");
    }
    oSDiv.onclick = function (event) {
        event = event || window.event;
        // event.stopPropagation(); // Advanced browser
        // event.cancelBubble = true; // Low-level browsers
        if(event.cancelBubble){
            event.cancelBubble = true;
        }else{
            event.stopPropagation();
        }
        console.log("son");
    }
</script>
</body>
</html>
Copy the code

Discrimination of different in-and-out events

The difference is whether bubble (or capture) is triggered

  1. Difference between onMouseOver and onMouseEnter
    • Onmouseover moves into the child element, and the parent element’s move event is also triggered
    • Onmouseenter moves into the child element. The move event for the parent element is not triggered
  2. Onmouseout and onmouseleave
    • Onmouseout moves out to the child element, and the parent element’s move event is also triggered
    • Onmouseleave moves out of the child element, and the parent element’s move event is not triggered
  3. Simply put, Enter and Leave are cleaner
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>44-JavaScript- Move in, move out event distinction</title>
    <style>* {margin: 0;
            padding: 0;
        }
        .father{
            width: 300px;
            height: 300px;
            background: red;
        }
        .son{
            width: 150px;
            height: 150px;
            background: blue;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son"></div>
</div>
<script>
    let oFDiv = document.querySelector(".father");
    let oSDiv = document.querySelector(".son");
    /* oFDiv.onmouseover = function () { console.log("father"); } oSDiv.onmouseover = function () { console.log("son"); } * /
    /* oFDiv.onmouseenter = function () { console.log("father"); } oSDiv.onmouseenter = function () { console.log("son"); } * /
    oFDiv.onmouseleave = function () {
        console.log("father");
    }
    oSDiv.onmouseleave = function () {
        console.log("son");
    }
</script>
</body>
</html>
Copy the code

Get element positions by events

  • OffsetX /offsetY: The position of the event trigger relative to the upper left origin of the current element itself
  • ClientX /clientY: Location of the event trigger relative to the viewable area of the browser (not supported by ancient browsers)
  • Note:
    • The display area does not include parts that scroll out (less used in this development)
  • screenX/screenY: The position of the event trigger relative to the screen
  • PageX /pageY: The position of the event trigger relative to the entire page (gets the same value as clientX/clientY when the page is not scrolling)

The details are

  • Return false when calling the event method to disable the default event, or event.preventDefault() will work

  • If you want to retrieve the input from the query input tag object, you can only use its value attribute

    HTML can set custom tag attributes for tags, you can use javascript,

    You can even add custom attribute tags to the specified DOM using JS

  • JS returns true/false if the attribute name of the HTML tag is the same as the value name, but if the data is set to input by code, the onInput event is not raised

  • Compatibility with ancient browsers is all you need to know

Mobile event

Mobile side specific event objects

  1. Touch event object
    • The touch event on the mobile terminal is also an event, so the system will automatically pass an event object to us when it is triggered
  2. The three more important children of the touch event object on the mobile side
    1. Touches: A list of all fingers on the current screen
    2. TargetTouches: Saves all finger lists on the current element (this is used more often)
    3. ChangedTouches: A finger touched or moved away from the current screen

Mobile endpoint penetration problem

  1. Mobile endpoint penetration problem
    • When one element overrides another, the overridden element listens for the ==touch== event, while the following element listens for the ==click== event
    • And when the touch event is triggered, the overridden element disappears, and the dot penetration problem occurs
  2. The cause of the mobile endpoint penetration problem
    1. When a finger touches the screen, the system generates two events, one for touch and one for click
    2. The touch event executes first and then disappears from the document
    3. The click event has a 100-300ms delay, so it is executed later.(Not for the right reason, but I added Content =”scalable= No “)
    4. But when the click event is executed, the element that triggered it has disappeared. The corresponding position is now the following element, so the click event for the following element is fired
  3. Mobile endpoint penetration solution added in touch eventsevent.preverDefault(); Stop the spread of events
<! DOCTYPEhtml>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
		<title>10- Mobile endpoint penetration problem</title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}
			div {
				text-align: center;
				font-size: 40px;
			}
			.click {
				width: 300px;
				height: 300px;
				background: red;
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
				top: 100px;
			}
			.tap {
				width: 200px;
				height: 200px;
				background: blue;
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
				top: 150px;
			}
		</style>
	</head>
	<body>
		<div class="click">click</div>
		<div class="tap">tap</div>
        <! -- The two elements are at the same level, but the two blocks overlap when presented -->
		<script>
			let oClick = document.querySelector(".click");
			let oTap = document.querySelector(".tap");

			oTap.ontouchstart = function (event) {
				this.style.display = "none";
				event.preventDefault(); // Prevent the event from spreading
			};
			oClick.onclick = function () {
				console.log("click");
			};
		</script>
	</body>
</html>
Copy the code