当前位置:网站首页>JS --- detailed explanation of JS DOM (IV)

JS --- detailed explanation of JS DOM (IV)

2022-07-06 15:22:00 Cirrod

1、DOM brief introduction

1.1、 What is? DOM

Document object model (Document Object Model, abbreviation DOM), yes W3C The Organization recommends dealing with extensible markup languages (HTML perhaps XML) Standard programming interface

W3C A series of DOM Interface , Through these DOM Interface can change the content of a web page 、 Structure and pattern .

 

file : A page is a document ,DOM Use in doucument To express

Elements : All tags in the page are elements ,DOM Use in element Express

node : Everything in a web page is a node ( label , attribute , Text , Notes, etc. ),DOM Use in node Express

DOM Think of all the above as objects

2、 Get elements

2.1、 How to get page elements

DOM In our actual development, it is mainly used to operate elements .

How do we get the elements in the page ?

There are several ways to get the elements in the page :

according to ID obtain

Get... According to the tag name

adopt HTML5 New method to get

Special element acquisition

2.2、 according to ID obtain

Use getElementByld() Method to get the band ID The element object of

doucument.getElementByld('id name ')

Use console.dir() You can print the element object we get , Better view the properties and methods in the object .

Example

<div id="time">2019-9-9</div>

<script>

// 1. Because we load document pages from top to bottom , So you have to have a label first , therefore script Write it under the label 

// 2.get  get  element  Elements  by  adopt   Hump nomenclature 

// 3. Parameters  id Is a case sensitive string 

// 4. It returns an element object 

var timer = document.getElementById('time');

console.log(timer);

// 5. console.dir  Print our element objects , Better view the properties and methods inside 

console.dir(timer);

</script>

2.3、 Get... According to the tag name

Get... According to the tag name , Use getElementByTagName() Method returns a collection of objects with the specified tag name

doucument.getElementsByTagName(' Tag name ');

Because what you get is a collection of objects , So if we want to manipulate the elements inside, we need to traverse

Get that the element object is dynamic

What is returned is the collection of obtained element objects , Store... As a pseudo array

If you can't get the element , Returns an empty pseudo array ( Because we can't get the object )

<ul>

<li> Know no know no , I've been waiting for you for a long time </li>

<li> Know no know no , I've been waiting for you for a long time </li>

<li> Know no know no , I've been waiting for you for a long time </li>

<li> Know no know no , I've been waiting for you for a long time </li>

<li> Know no know no , I've been waiting for you for a long time </li>

</ul>
<script>

// 1. What is returned is the collection of obtained element objects   Store... As a pseudo array 

var lis = document.getElementsByTagName('li');

console.log(lis);

console.log(lis[0]);

// 2. In turn, print , Traverse 

for (var i = 0; i < lis.length; i++) {

console.log(lis[i]);

}

// 3. If there are only  1  individual  li, The return is still in the form of pseudo array 

// 4. If there is no such element in the page , Returns an empty pseudo array 

</script>

2.4、 Get... According to the tag name

You can also get an element according to the tag name ( Parent element ) All internal child elements with specified tag names , The parent element itself is not included in the acquisition

element.getElementsByTagName(' Tag name ')



ol.getElementsByTagName('li');

Be careful : The parent element must be a single object ( You must specify which element object ), The parent element itself is not included in the acquisition

<script>

    //element.getElementsByTagName(' Tag name ');  The parent element must be the specified single element 

var ol = document.getElementById('ol');

console.log(ol.getElementsByTagName('li'));

</script>

2.5、 adopt H5 Add a new method to get

①getElementsByClassName

Returns the collection of element objects according to the class name

document.getElementsByClassName(' Class name ')

document.getElementsByClassName(' Class name ');

②document.querySelector

Returns the first element object... Based on the specified selector

document.querySelector(' Selectors ');



//  Remember that the selector inside needs to be signed 

//  Class selectors .box

// id Selectors  #nav

var firstBox = document.querySelector('.box');

③document.querySelectorAll

Returns all element objects according to the specified selector

document.querySelectorAll(' Selectors ');

Be careful :

querySelector and querySelectorAll The selector inside needs to be signed , such as : document.querySelector('#nav');

④ Example

<script>

// 1. getElementsByClassName  Get a collection of certain elements according to the class name 

var boxs = document.getElementsByClassName('box');

console.log(boxs);

// 2. querySelector  Returns the first element object of the specified selector   Bear in mind   The selector inside needs to be signed  .box #nav

var firstBox = document.querySelector('.box');

console.log(firstBox);

var nav = document.querySelector('#nav');

console.log(nav);

var li = document.querySelector('li');

console.log(li);

// 3. querySelectorAll() Returns a collection of all element objects of the specified selector 

var allBox = document.querySelectorAll('.box');

console.log(allBox);

var lis = document.querySelectorAll('li');

console.log(lis);

</script>

2.6、 Get special elements

① obtain body Elements

return body Element object

document.body;

② obtain html Elements

return html Element object

document.documentElement;

3、 The basis of the event

3.1、 Summary of events

JavaScript It gives us the ability to create dynamic pages , And events can be JavaScript Detected behavior .

Simple understanding : Trigger — Response mechanism .

Every element in a web page can generate something that can trigger JavaScript Events , for example , We can generate an event when the user clicks a button , And then do something .

3.2、 Three elements of the event

Event source ( who )

Event type ( What event )

Event handler ( Zuosa )

<script>

//  Click a button , Pop-up dialog box 

// 1.  The event is made up of three parts   Event source   Event type   Event handler   We also call it the three elements of an event 

//(1)  Event source   The event is triggered by   who   Button 

var btn = document.getElementById('btn');

//(2)  Event type   How to trigger   What event   For example, mouse click (onclick)  Or mouse over   Or press the keyboard 

//(3)  Event handler   By means of a function assignment   complete 

btn.onclick = function() {

alert(' Some autumn fragrance ');

}

</script>

3.3、 Steps to execute the event

Get the event source

Registration events ( The binding event )

Add event handler ( Take the form of function assignment )

<script>

//  Perform event steps 

//  Click on div  Console output   I was chosen 

// 1.  Get the event source 

var div = document.querySelector('div');

// 2. The binding event   Registration events 

// div.onclick

// 3. Add event handler 

div.onclick = function() {

console.log(' I was chosen ');

}

</script>

3.4、 Mouse events

Mouse events The trigger condition
onclick Click the left mouse button to trigger
onmouseover Mouse over trigger
onmouseout Mouse off trigger
onfocus Get mouse focus trigger
onblur Lose mouse focus trigger
onmousemove Mouse movement trigger
onmouseup Mouse pop up trigger
onmousedown Mouse down trigger

4、 Operational elements

JavaScript Of DOM The operation can change the content of the web page 、 Structure and pattern , We can use DOM Manipulate elements to change the contents of elements 、 Properties, etc . Note that the following are attributes

4.1、 Change element content

Content from start to end , But it removes html label , At the same time, spaces and line breaks are removed .

element.innerText

Everything from the start position to the end position , Include HTML label , Keep spaces and line breaks at the same time

 

element.innerHTML

<body>

<div></div>

<p>

 I am character. 

<span>123</span>

</p>



<script>

// innerText  and  innerHTML The difference between 

// 1. innerText  Don't recognize html label , Remove spaces and line breaks 

var div = document.querySelector('div');

div.innerText = '<strong> It's today :</strong> 2019';

// 2. innerHTML  distinguish html label   Keep spaces and line breaks 

div.innerHTML = '<strong> It's today :</strong> 2019';

//  These two properties are readable and writable   You can get the content of the element 

var p = document.querySelector('p');

console.log(p.innerText);

console.log(p.innerHTML);

</script>

</body>

4.2、 Change element properties

// img. attribute 

img.src = "xxx";



input.value = "xxx";

input.type = "xxx";

input.checked = "xxx";

input.selected = true / false;

input.disabled = true / false;

4.3、 Change style properties

We can go through JS Change the size of the element 、 Color 、 Position, etc .

Inline style operation

// element.style

div.style.backgroundColor = 'pink';

div.style.width = '250px';

Class name style operation

// element.className

Be careful :

JS The style inside adopts the hump naming method , such as fontSize ,backgroundColor

JS modify style Style operation , What's produced is the in line style ,CSS The weight is relatively high

If the style is changed a lot , You can change the element style by operating the class name

class Because it's a reserved word , Therefore use className To manipulate the element class name attribute

className Will directly change the class name of the element , Will override the original class name

<body>

<div class="first"> Text </div>

<script>

// 1.  Use  element.style  Get the modified element style   If there are fewer styles   perhaps   Use when the function is simple 

var test = document.querySelector('div');

test.onclick = function() {

// this.style.backgroundColor = 'purple';

// this.style.color = '#fff';

// this.style.fontSize = '25px';

// this.style.marginTop = '100px';

//  Let's change the class name of the current element to  change



// 2.  We can go through   Modify element className Change the style of the element   Suitable for more styles or complex functions 

// 3.  If you want to keep the original class name , We can do that   Multi class name selector 

// this.className = 'change';

this.className = 'first change';

}

</script>

</body>

4.4、 summary

 

4.5、 Exclusive thoughts

If you have the same set of elements , We want an element to implement a certain style , Need to use the exclusive thought algorithm of the loop :

All elements clear the style ( Kill the others )

Style the current element ( Leave me alone )

Note that the order cannot be reversed , First kill the others , Set yourself up

 

<body>

<button> Button 1</button>

<button> Button 2</button>

<button> Button 3</button>

<button> Button 4</button>

<button> Button 5</button>

<script>

// 1.  Get all button elements 

var btns = document.getElementsByTagName('button');

// btns The result is a pseudo array   Every element in it  btns[i]

for (var i = 0; i < btns.length; i++) {

btns[i].onclick = function() {

// (1)  Let's remove all the button background colors first   Get rid of everyone 

for (var i = 0; i < btns.length; i++) {

btns[i].style.backgroundColor = '';

}

// (2)  Then let the current element background color be pink  Leave me alone 

this.style.backgroundColor = 'pink';



}

}

//2.  First, exclude others , Then set your own style   This thought of excluding others makes us an exclusive thought 

</script>

</body>

4.6、 Custom properties

4.6.1、 Get attribute value

Get built-in property values ( The attribute of the element itself )

element. attribute ;

Get custom properties

element.getAttribute(' attribute ');

4.6.2、 Setting property values

Set built-in property values

element. attribute  = ' value ';

It mainly sets custom properties

element.setAttribute(' attribute ');

4.6.3、 Remove properties

element.removeAttribute(' attribute ');

<body>

<div id="demo" index="1" class="nav"></div>

<script>

var div = document.querySelector('div');

// 1.  Gets the attribute value of the element 

// (1) element. attribute 

console.log(div.id);

//(2) element.getAttribute(' attribute ') get Get... Get  attribute  Attribute meaning   The properties added by our programmers are called custom properties  index

console.log(div.getAttribute('id'));

console.log(div.getAttribute('index'));

// 2.  Set element attribute value 

// (1) element. attribute = ' value '

div.id = 'test';

div.className = 'navs';

// (2) element.setAttribute(' attribute ', ' value ');  It is mainly aimed at custom attributes 

div.setAttribute('index', 2);

div.setAttribute('class', 'footer'); // class  special   It says class  No className

// 3  Remove properties  removeAttribute( attribute )

div.removeAttribute('index');

</script>

</body>

4.7、H5 Custom properties

Custom attribute purpose :

Save and save data , Some data can be saved to the page instead of the database

Some custom attributes are easily ambiguous , It's not easy to determine whether it's built-in or custom , therefore H5 With the rules

2.8.1 Set up H5 Custom properties

H5 Specify custom attributes data- Start as a property name and assign a value

<div data-index = "1"></>

//  Or use JavaScript Set up 

div.setAttribute('data-index',1);

2.8.2 obtain H5 Custom properties

Compatibility gains element.getAttribute('data-index')

H5 Newly added :element.dataset.index or element.dataset['index'] IE11 Just started to support

<body>

<div getTime="20" data-index="2" data-list-name="andy"></div>

<script>

var div = document.querySelector('div');

console.log(div.getAttribute('getTime'));

div.setAttribute('data-time', 20);

console.log(div.getAttribute('data-index'));

console.log(div.getAttribute('data-list-name'));

// h5 New method to get custom attributes   It can only get data- At the beginning 

// dataset  It's a collection that holds all the information in data Custom properties at the beginning 

console.log(div.dataset);

console.log(div.dataset.index);

console.log(div.dataset['index']);

//  If there are multiple custom attributes - Linked words , We take... When we get it   Hump nomenclature 

console.log(div.dataset.listName);

console.log(div.dataset['listName']);

</script>

</body>

5、 Node operation

There are usually two ways to get elements :

1. utilize DOM The method provided gets the element 2. Get elements by using node hierarchy
document.getElementById() Using parent-child sibling node relationship to obtain elements
document.getElementsByTagName() Strong logic , But compatibility is poor
document.querySelector etc.
The logic is not strong , tedious

Both of these methods can get element nodes , We'll all use it later , But the node operation is simpler

General , A node has at least three basic attributes

5.1、 Node Overview

Everything in a web page is a node ( label 、 attribute 、 Text 、 Notes, etc. ), stay DOM in , Node usage node To express .

HTML DOM All nodes in the tree can pass through JavaScript Visit , all HTML Elements ( node ) Can be modified , You can also create or delete .

 

General , Nodes have at least nodeType( Node type )、nodeName( The name of the node ) and nodeValue( Node values ) These three basic attributes .

Element nodes :nodeType by 1

Attribute node :nodeType by 2

Text node :nodeType by 3( Text nodes include text 、 Space 、 Line break, etc )

We're actually developing it , Node operations mainly operate on element nodes

utilize DOM Trees can divide nodes into different hierarchical relationships , Common is the hierarchical relationship between father, son and brother .

5.2、 Parent node

node.parentNode

parentNode Property can return the parent node of a node , Note that it is the nearest parent node

If the specified node has no parent node, return null

<body>

<!--  Advantages of nodes  -->

<div> I am a div</div>

<span> I am a span</span>

<ul>

<li> I am a li</li>

<li> I am a li</li>

<li> I am a li</li>

<li> I am a li</li>

</ul>

<div class="demo">

<div class="box">

<span class="erweima">×</span>

</div>

</div>



<script>

// 1.  Parent node  parentNode

var erweima = document.querySelector('.erweima');

// var box = document.querySelector('.box');

//  The result is the parent node closest to the element ( Dad )  If the parent node cannot be found, it returns  null

console.log(erweima.parentNode);

</script>

</body>

5.3、 The child node

parentNode.childNodes( standard )

parentNode.childNodes Returns a collection of children of a specified node , The set is an instant update set

The return value contains all child nodes , Include element nodes , Text nodes, etc

If you only want to get the element nodes inside , It needs to be dealt with specially . Therefore, we generally do not advocate the use of childNodes

parentNode.children( Nonstandard )

parentNode.children Is a read-only property , Returns all child element nodes

It only returns child element nodes , The remaining nodes do not return ( This is what we focus on )

although children It's a non-standard , But it's supported by various browsers , So we can use it safely

<body>

<ul>

<li> I am a li</li>

<li> I am a li</li>

<li> I am a li</li>

<li> I am a li</li>

</ul>

<ol>

<li> I am a li</li>

<li> I am a li</li>

<li> I am a li</li>

<li> I am a li</li>

</ol>

<script>

// DOM  Methods provided (API) obtain 

var ul = document.querySelector('ul');

var lis = ul.querySelectorAll('li');

// 1.  Child node  childNodes  All child nodes   contain   Element nodes   Text nodes and so on 

console.log(ul.childNodes);

console.log(ul.childNodes[0].nodeType);

console.log(ul.childNodes[1].nodeType);

// 2. children  Get all child element nodes   It is also commonly used in our actual development 

console.log(ul.children);

</script>

</body>

5.3.1、 The first child node

parentNode.firstChild

firstChild Return to the first child node , Return if not found null

Again , It also contains all the nodes

5.3.2、 The last child node

parentNode.lastChild

lastChild Returns the last child node , Return if not found null

Again , It also contains all the nodes

<body>

<ol>

<li> I am a li1</li>

<li> I am a li2</li>

<li> I am a li3</li>

<li> I am a li4</li>

<li> I am a li5</li>

</ol>

<script>

var ol = document.querySelector('ol');

// 1. firstChild  First child node   Whether it's a text node or an element node 

console.log(ol.firstChild);

console.log(ol.lastChild);

// 2. firstElementChild  Returns the first child node  ie9 To support 

console.log(ol.firstElementChild);

console.log(ol.lastElementChild);

// 3.  The actual development of writing   There is no compatibility problem and the first child element is returned 

console.log(ol.children[0]);            // The first child element node 

console.log(ol.children[ol.children.length - 1]);// The last child element node 

</script>

</body>

 

5.3.3、 The first child node ( Compatibility )

parentNode.firstElementChild

firstElementChild Return to the first child node , Return if not found null

Compatibility issues ,IE9 The above supports

5.3.4、 The last child node ( Compatibility )

parentNode.lastElementChild

lastElementChild Returns the last child node , Return if not found null

Compatibility issues ,IE9 The above supports

5.3.5、 Solution

In development ,firstChild and lastChild Include other nodes , Inconvenient operation , and firstElementChild and lastElementChild There's a compatibility issue , So how do we get the first child element node or the last child element node ?

Solution

If you want the first child element node , have access to parentNode.chilren[0]

If you want the last child element node , have access to

// The number of array elements minus 1 Is the index number of the last element

parentNode.chilren[parentNode.chilren.length - 1]

Example :

<body>

<ol>

<li> I am a li1</li>

<li> I am a li2</li>

<li> I am a li3</li>

<li> I am a li4</li>

</ol>

<script>

var ol = document.querySelector('ol');

// 1.firstChild  Get the of the first child node , Contains text nodes and element nodes 

console.log(ol.firstChild);

//  The text node is returned  #text( The first line feed node )

console.log(ol.lastChild);

//  The text node is returned  #text( The last node )

// 2. firstElementChild  Returns the first child element node 

console.log(ol.firstElementChild);

// <li> I am a li1</li>

//  The first 2 Two methods have compatibility problems , need IE9 The above supports 

// 3. In development , There are no compatibility issues , Returns the first child element 

console.log(ol.children[0]);

// <li> I am a li1</li>

console.log(ol.children[3]);

// <li> I am a li4</li>

//  When inside li When the number is not unique , Write this when you need to get the last node 

console.log(ol.children[ol.children.length - 1]);

</script>

</body>

5.4、 Brother node

5.4.1、 Next sibling node

node.nextSibling

nextSibling Returns the next sibling node of the current element , Return if not found null

Again , It also contains all the nodes

5.4.2、 Last sibling node

node.previousSibling

previousSibling Returns the previous sibling element node of the current element , Return if not found null

Again , It also contains all the nodes

5.4.3、 Next sibling node ( Compatibility )

node.nextElementSibling

nextElementSibling Returns the next sibling element node of the current element , Return if not found null

Compatibility issues ,IE9 To support

5.4.4、 Last sibling node ( Compatibility )

node.previousElementSibling

previousElementSibling Returns the previous sibling element node of the current element , Return if not found null

Compatibility issues ,IE9 To support

Example

<body>

<div> I am a div</div>

<span> I am a span</span>

<script>

var div = document.querySelector('div');

// 1.nextSibling  Next sibling node   Contains element nodes or   Text nodes and so on 

console.log(div.nextSibling);        // #text

console.log(div.previousSibling);    // #text

// 2. nextElementSibling  Get the next sibling node 

console.log(div.nextElementSibling);    //<span> I am a span</span>

console.log(div.previousElementSibling);//null

</script>

</body>

How to solve compatibility problems ?

answer : Encapsulate a compatible function

function getNextElementSibling(element) {

var el = element;

while(el = el.nextSibling) {

if(el.nodeType === 1){

return el;

}

}

return null;

}

5.5、 Create nodes

document.createElement('tagName');

document.createElement() Method created by tagName designated HTML Elements

Because these elements didn't exist , It's dynamically generated according to our needs , So we also call it dynamic creation of element nodes

5.5.1、 Add a node

node.appendChild(child)

node.appendChild() Method adds a node to the end of the child node list of the specified parent node . Be similar to CSS Inside after Pseudo elements .

node.insertBefore(child, Specify elements )

node.insertBefore() Method to add a node in front of the specified child node of the parent node . Be similar to CSS Inside before Pseudo elements .

Example

<body>

<ul>

<li>123</li>

</ul>

<script>

// 1.  Create a node element node 

var li = document.createElement('li');

// 2.  Add a node  node.appendChild(child) node  Parent  child  It's a child   Append element after   Similar to... In an array push

//  Get your father first ul

var ul = document.querySelector('ul');

ul.appendChild(li);

// 3.  Add a node  node.insertBefore(child,  Specify elements );

var lili = document.createElement('li');

ul.insertBefore(lili, ul.children[0]);

// 4.  We want to add a new element to the page in two steps : 1.  Create elements  2.  Additive elements 

</script>

</body>

5.5.2、 Delete node

node.removeChild(child)

node.removeChild() Methods from DOM Delete a child node in the , Return the deleted node

5.5.3、 Replication node ( Clone node )

node.cloneNode()

node.cloneNode() Method returns a copy of the node that called the method . Also known as clone nodes / Copy node

If the parenthesis parameter is empty or false , It's a light copy , That is, only clone the replication node itself , Don't clone the child nodes inside

If the bracket parameter is true , Is a deep copy , It will copy the node itself and all its children

Example

<body>

<ul>

<li>1111</li>

<li>2</li>

<li>3</li>

</ul>

<script>

var ul = document.querySelector('ul');

// 1. node.cloneNode();  Parentheses are empty or contain false  Shallow copy   Just copy the label, not the content 

// 2. node.cloneNode(true);  Parentheses are true  Deep copy   Copy the label, copy the contents 

var lili = ul.children[0].cloneNode(true);

ul.appendChild(lili);

</script>

</body>

 

 

5.5.4、 Interview questions

The difference between the three dynamic creation elements

doucument.write()

element.innerHTML

document.createElement()

difference :

document.write() It's a content stream that writes content directly to the page , But the document flow is finished , It causes the page to be redrawn completely

innerHTML It's writing content into something DOM node , It doesn't cause the page to redraw completely

innerHTML It's more efficient to create multiple elements ( Don't splice strings , Take the form of array splicing ), The structure is a little more complicated

<body>

<div class="innner"></div>

<div class="create"></div>

<script>

// 2. innerHTML  Create elements 

var inner = document.querySelector('.inner');

// 2.1 innerHTML  Use the string splicing method 

for (var i = 0; i <= 100; i++) {

inner.innerHTML = '<a href="#"> Baidu </a>';

}

// 2.2 innerHTML  In the form of an array 

var arr = [];

for (var i = 0; i <= 100; i++) {

arr.push('<a href="#"> Baidu </a>');

}

inner.innerHTML = arr.join('');



// 3.document.createElement()  Create elements 

var create = document.querySelector('.create');

var a = document.createElement('a');

create.appendChild(a);

</script>

</body>

createElement() Creating multiple elements is a little less efficient , But the structure is clearer

summary : Different browsers , innerHTML More efficient than createElement high

6、DOM The core

about DOM operation , We mainly focus on the operation of sub elements , There are mainly

establish

increase

Delete

Change

check

Attribute operation

Time operation

6.1、 establish

document.write

innerHTML

createElement

6.2、 increase

appendChild

insertBefore

6.3、 Delete

removeChild

6.4、 Change

Major changes dom Element properties of ,dom Content of element 、 attribute 、 Form values, etc

Modify element properties :src、href、title etc.

Modify the content of common elements :innerHTML、innerText

Modify form elements :value、type、disabled

Modify element styles :style、className

6.5、 check

Mainly get the query dom The elements of

DOM Provided API Method :getElementById、getElementsByTagName ( Old usage , Not recommended )

H5 New methods provided :querySelector、querySelectorAll ( promote )

Use node operations to get elements : Father (parentNode)、 Son (children)、 Brother (previousElementSibling、nextElementSibling) promote

6.6、 Attribute operation

It is mainly aimed at custom attributes

setAttribute: Set up dom The attribute value

getAttribute: obtain dom The attribute value

removeAttribute: Remove properties

7、 Event advanced

7.1、 Registration events ( The binding event )

Add events to the element , It is called registration event or binding event .

There are two ways to register Events : Traditional methods and methods monitor registration methods

Traditional way of registration Methods listen to the registration method
utilize on The first event onclickw3c Standard recommended method
<button onclick = "alert("hi")"></button>addEventListener() It's a way
btn.onclick = function() {}IE9 Previous IE This method is not supported , You can use attachEvent() Instead of
characteristic : The uniqueness of the registration event characteristic : Multiple listeners can be registered for the same element and the same event
Only one processing function can be set for the same event of an element , The last registered handler will override the previous one Follow the order of registration

①addEventListener Event monitoring mode

eventTarget.addEventListener() Method to register the specified listener to eventTarget( Target audience ) On

When the object triggers the specified event , The event handler is executed

eventTarget.addEventListener(type,listener[,useCapture])

This method takes three parameters :

type: Event type string , such as click,mouseover, Be careful not to bring on

listener: Event handler , Event time , The listener function will be called

useCapture: Optional parameters , It's a Boolean value , The default is false. By the end DOM After event flow , Let's study further

<body>

<button> Traditional registration Events </button>

<button> Method to listen for registration events </button>

<button>ie9 attachEvent</button>

<script>

var btns = document.querySelectorAll('button');

// 1.  Register events in the traditional way 

btns[0].onclick = function() {

alert('hi');

}

btns[0].onclick = function() {

alert('hao a u');

}

// 2.  Event listener registers events  addEventListener

// (1)  The event type inside is string   So use quotation marks   And without on

// (2)  The same element   Multiple listeners can be added to the same event ( Event handler )

btns[1].addEventListener('click', function() {

alert(22);

})

btns[1].addEventListener('click', function() {

alert(33);

})

// 3. attachEvent ie9 Previous versions support 

btns[2].attachEvent('onclick', function() {

alert(11);

})

</script>

</body>

②attachEvent Event monitoring mode ( compatible )
eventTarget.attachEvent() Method to register the specified listener to  eventTarget( Target audience )  On 

 When the object triggers the specified event , The specified callback function will be executed 

eventTarget.attachEvent(eventNameWithOn,callback)

1

 This method takes two parameters :

eventNameWithOn: Event type string , such as  onclick 、onmouseover , I'll take it here  on

callback:  Event handler , When the target triggers an event, the callback function is called 

ie9 Previous versions support 

③ Register event compatibility solutions 
 The principle of compatibility handling : Take care of most browsers first , And then deal with special browsers 

function addEventListener(element, eventName, fn) {

//  Determine whether the current browser supports it  addEventListener  Method 

if (element.addEventListener) {

element.addEventListener(eventName, fn); //  The third parameter   The default is false

} else if (element.attachEvent) {

element.attachEvent('on' + eventName, fn);

} else {

//  amount to  element.onclick = fn;

element['on' + eventName] = fn;

}

7.2、 Delete event ( Unbind event )

7.2.1、removeEventListener Delete event mode

eventTarget.removeEventListener(type,listener[,useCapture]);

This method takes three parameters :

type: Event type string , such as click,mouseover, Be careful not to bring on

listener: Event handler , Event time , The listener function will be called

useCapture: Optional parameters , It's a Boolean value , The default is false. By the end DOM After event flow , Let's study further

7.2.2、detachEvent Delete event mode ( compatible )

eventTarget.detachEvent(eventNameWithOn,callback);

This method takes two parameters :

eventNameWithOn: Event type string , such as onclick 、onmouseover , I'll take it here on

callback: Event handler , When the target triggers an event, the callback function is called

ie9 Previous versions support

7.2.3、 Traditional event deletion method

eventTarget.onclick = null;

Event deletion example :

<body>

<div>1</div>

<div>2</div>

<div>3</div>

<script>

var divs = document.querySelectorAll('div');

divs[0].onclick = function() {

alert(11);

// 1.  Delete events in the traditional way 

divs[0].onclick = null;

}

// 2.removeEventListener  Delete event 

divs[1].addEventListener('click',fn); // Inside fn You don't need to call with parentheses 



function fn(){

alert(22);

divs[1].removeEventListener('click',fn);

}

// 3.IE9  Delete event mode in 

divs[2].attachEvent('onclick',fn1);

function fn1() {

alert(33);

divs[2].detachEvent('onclick',fn1);

}

</script>



</body>

7.2.4、 Remove event compatibility solution

function removeEventListener(element, eventName, fn) {

//  Determine whether the current browser supports it  removeEventListener  Method 

if (element.removeEventListener) {

element.removeEventListener(eventName, fn); //  The third parameter   The default is false

} else if (element.detachEvent) {

element.detachEvent('on' + eventName, fn);

} else {

element['on' + eventName] = null;

}

7.3、DOM Flow of events

The event flow describes the order in which events are received from the page

Events are propagated between element nodes in a specific order when they occur , This communication process is DOM Flow of events

 

Event Bubbling : IE Put forward at the earliest , The event is received by the most specific element at the beginning , Then spread up to DOM The process of the topmost node .

Event capture : Netscape first proposed , from DOM The top node starts , Then it propagates step by step down to the process of receiving the most specific elements .

Deepen the understanding :

We threw a stone into the water , First of all, it will have a downward process , This process can be understood as the most specific element from the top to the event ( The target point ) Capture process of ; Then bubbles will appear , It will be at the lowest point ( Most specific elements ) And then it floats to the surface , This process is equivalent to event bubbling .

 

7.3.1、 Capture phase

document -> html -> body -> father -> son

Two boxes nested , A parent box, a child box , Our requirement is to pop up when we click on the parent box father , When you click on the sub box, it pops up son

<body>

<div class="father">

<div class="son">son The box </div>

</div>

<script>

// dom  Flow of events   Three stages 

// 1. JS  Only one stage of capture or bubbling can be performed in the code .

// 2. onclick  and  attachEvent(ie)  You can only get the bubbling stage .

// 3.  Capture phase   If addEventListener  The third parameter is  true  Then it's in the capture stage  document -> html -> body -> father -> son

var son = document.querySelector('.son');

son.addEventListener('click', function() {

alert('son');

}, true);

var father = document.querySelector('.father');

father.addEventListener('click', function() {

alert('father');

}, true);

</script>

</body>

But because DOM The impact of flow , We click on the sub box , It will pop up first father, Then pop up son

This is because the capture phase consists of DOM The top node starts , Then it propagates down to the most specific element to receive

document -> html -> body -> father -> son

First look at document Events , No, ; Look again html Events , No, ; Look again body Events , No, ; Look again father Events , If there is, execute it first ; Look again son Events , Re execution .

7.3.2、 bubbling phase

son -> father ->body -> html -> document

<body>

<div class="father">

<div class="son">son The box </div>

</div>

<script>

        // 4.  bubbling phase   If addEventListener  The third parameter is  false  perhaps   Omit   Then it is in the bubbling stage  son -> father ->body -> html -> document

var son = document.querySelector('.son');

son.addEventListener('click', function() {

alert('son');

}, false);

var father = document.querySelector('.father');

father.addEventListener('click', function() {

alert('father');

}, false);

document.addEventListener('click', function() {

alert('document');

})

</script>

</body>

We click on the sub box , Will pop up son、father、document

This is because at the beginning of the bubbling phase, it is received by the most specific element , Then spread up to DOM Top node

son -> father ->body -> html -> document

7.3.3、 Summary

JS Only one stage of capture or bubbling can be performed in the code

onclick and attachEvent You can only get the bubbling stage

addEventListener(type,listener[,useCapture]) The third parameter is if true, Indicates that the event handler is called during the event capture phase ; If it is false ( No, the default is false), Indicates that the event handler is called during the event bubbling phase

We rarely use event capture in actual development , We're more concerned about the bubbling of events .

Some events are not bubbling , such as onblur、onfocus、onmouseenter、onmouseleave

7.4、 Event object

eventTarget.onclick = function(event) {

//  This  event  It's the object of the event , We also like to write  e  perhaps  evt

}

eventTarget.addEventListener('click', function(event) {

//  This  event  It's the object of the event , We also like to write  e  perhaps  evt

})

Official explanation :event Object represents the state of the event , For example, the state of keyboard keys 、 Mouse position 、 Mouse button status

Simple understanding :

After the event , A collection of information data related to an event is put into this object

This object is the event object event, It has many properties and methods , such as “

Who bound this event

If the mouse triggers an event , You'll get information about the mouse , Such as mouse position

If the keyboard triggers an event , You'll get information about the keyboard , If you press which key

This event It's a formal parameter , The system helps us set it as an event object , There is no need to pass arguments in the past

When we register Events , event The object will be created automatically by the system , And pass it to the event listener in turn ( Event handler )

<body>

<div>123</div>

<script>

//  Event object 

var div = document.querySelector('div');

div.onclick = function(e) {

// console.log(e);

// console.log(window.event);

// e = e || window.event;

console.log(e);





}

// 1. event  It's an event object   Write to our listener function   Inside the parentheses   When it comes to formal parameters 

// 2.  Event objects exist only when they have events , It is automatically created by the system for us , We don't need to pass parameters 

// 3.  Event object   yes   A collection of related data about our events   Related to the event   For example, the mouse click contains the relevant information of the mouse , Mouse coordinates , If it is a keyboard event, it contains the information of the keyboard event   such as   Judge that the user pressed that key 

// 4.  We can name this event object ourselves   such as  event 、 evt、 e

// 5.  There are also compatibility issues with event objects  ie678  adopt  window.event  Compatible writing  e = e || window.event;

</script>

</body>

7.4.1、 Compatibility scheme for event objects

There is a compatibility problem with the acquisition of the event object itself :

In the standard browser, the parameters passed by the browser to the method , Just define the formal parameters e I can get it .

stay IE6~8 in , The browser does not pass parameters to methods , If necessary , Need to window.event To find

solve :

e = e || window.event;

7.4.2、 Common properties and methods of event objects

Event object property method explain
e.target Returns the object that triggered the event standard
e.srcElement Returns the object that triggered the event Nonstandard ie6-8 Use
e.type Returns the type of the event such as click mouseover No on
e.cancelBubble This property prevents bubbling , Nonstandard ,ie6-8 Use
e.returnValue This property blocks the default behavior Nonstandard ,ie6-8 Use
e.preventDefault() This method blocks the default behavior standard For example, do not let the link jump
e.stopPropagation() To prevent a bubble standard

e.target and this The difference between :

this It's an event bound element , The caller of this function ( The element that binds this event )

e.target Is the element triggered by the event .

7.5、 Event objects prevent default behavior

<body>

<div>123</div>

<a href="http://www.baidu.com"> Baidu </a>

<form action="http://www.baidu.com">

<input type="submit" value=" Submit " name="sub">

</form>

<script>

//  Properties and methods of common event objects 

// 1.  Return event type 

var div = document.querySelector('div');

div.addEventListener('click', fn);

div.addEventListener('mouseover', fn);

div.addEventListener('mouseout', fn);



function fn(e) {

console.log(e.type);



}

// 2.  Blocking default behavior ( event )  Let the link not jump   Or let the submit button not submit 

var a = document.querySelector('a');

a.addEventListener('click', function(e) {

e.preventDefault(); // dom  Standard writing 

})

// 3.  Traditional registration methods 

a.onclick = function(e) {

//  Normal browser  e.preventDefault();  Method 

// e.preventDefault();

//  Lower version browser  ie678 returnValue  attribute 

// e.returnValue;

//  We can use return false  It also prevents default behavior   No compatibility issues   characteristic : return  The following code is not executed ,  And it's limited to the traditional way of registration 

return false;

alert(11);

}

</script>

</body>

4.4.5 Compatibility of event objects

There is a compatibility problem with the acquisition of the event object itself :

In the standard browser, the browser is the parameter passed to the method , Just define the formal parameters e I can get it

stay IE6 -> 8 in , The browser does not pass parameters to methods , If necessary , Need to window.event To find

Solution

e = e || window.event

<body>

<div>123</div>

<script>

//  Event object 

var div = document.querySelector('div');

div.onclick = function(e) {

// e = e || window.event;

console.log(e);

                //  There are also compatibility issues with event objects  ie678  adopt  window.event  Compatible writing  e = e || window.event;



}

</body>

7.7、 Event delegation

Event delegates are also called event proxies , stay jQuery It's called event delegation

The principle of event delegation

Not every child node sets up an event listener alone , Instead, the event listener is set on its parent node , Then use the bubble principle to influence the setting of each child node

<body>

<ul>

<li> Know no know no , I should have a bullet box in my hand !</li>

<li> Know no know no , I should have a bullet box in my hand !</li>

<li> Know no know no , I should have a bullet box in my hand !</li>

<li> Know no know no , I should have a bullet box in my hand !</li>

<li> Know no know no , I should have a bullet box in my hand !</li>

</ul>

<script>

//  The core principle of event delegation : Add listener to parent node ,  Use event bubbling to affect each child node 

var ul = document.querySelector('ul');

ul.addEventListener('click', function(e) {

// alert(' Know no know no , I should have a bullet box in my hand !');

// e.target  This can get the object we click 

e.target.style.backgroundColor = 'pink';

//  Who did you order , Just let someone style Inside backgroundColor The color changes to pink

})

</script>

</body>

The above cases : to ul Register click events , Then use the... Of the event object target To find the currently clicked li, Because click li, Events will bubble to ul On , ul There are registration events , The event listener is triggered .

7.8、 Common mouse events

Mouse events The trigger condition
onclick Click the left mouse button to trigger
onmouseover Mouse over trigger
onmouseout Mouse off trigger
onfocus Get mouse focus trigger
onblur Lose mouse focus trigger
onmousemove Mouse movement trigger
onmouseup Mouse pop up trigger
onmousedown Mouse down trigger

7.8.1、 Prohibit right mouse button and mouse selection

contextmenu It mainly controls when the context menu should be displayed , It is mainly used by programmers to cancel the default context menu

selectstart Disable mouse selection

<body>

<h1> I am a text that I don't want to share </h1>

<script>

// 1. contextmenu  We can disable the right-click menu 

document.addEventListener('contextmenu', function(e) {

e.preventDefault(); //  Blocking default behavior 

})

// 2.  Do not select text  selectstart

document.addEventListener('selectstart', function(e) {

e.preventDefault();



})

</script>

</body>

7.8.2、 Mouse event object

event Object represents the state of the event , A collection of information related to an event

At this stage, we mainly use the mouse event object MouseEvent And keyboard event objects KeyboardEvent.

Mouse event object explain
e.clientX Returns the position of the mouse relative to the viewable area of the browser window X coordinate
e.clientY Returns the position of the mouse relative to the viewable area of the browser window Y coordinate
e.pageX( a key ) Returns the mouse relative to the document page X coordinate IE9+ Support
e.pageY( a key ) Returns the mouse relative to the document page Y coordinate IE9+ Support
e.screenX Returns the position of the mouse relative to the computer screen X coordinate
e.screenY Returns the position of the mouse relative to the computer screen Y coordinate
<body>

<script>

//  Mouse event object  MouseEvent

document.addEventListener('click', function(e) {

// 1. client  The mouse is in the visible area x and y coordinate 

console.log(e.clientX);

console.log(e.clientY);

console.log('---------------------');



// 2. page  The mouse is on the page of the document x and y coordinate 

console.log(e.pageX);

console.log(e.pageY);

console.log('---------------------');



// 3. screen  The mouse is on the top of the computer screen x and y coordinate 

console.log(e.screenX);

console.log(e.screenY);



})

</script>

</body>

7.9、 Common keyboard events

Keyboard events The trigger condition
onkeyup Trigger when a keyboard key is released
onkeydown Trigger when a keyboard key is pressed
onkeypress Trigger when a keyboard key is pressed , But it doesn't recognize function keys , such as ctrl shift Arrow, etc

If you use addEventListener No need to add on

onkeypress And the front 2 The difference is , It does not recognize function keys , For example, left and right arrows ,shift etc.

The order of execution of the three events is : keydown – keypress — keyup

<body>

<script>

//  Common keyboard events 

//1. keyup  It's triggered when the button pops up 

// document.onkeyup = function() {

// console.log(' I bounced up ');



// }

document.addEventListener('keyup', function() {

console.log(' I bounced up ');

})



//3. keypress  It's triggered when the key is pressed   Can't recognize function keys   such as  ctrl shift  Left and right arrows 

document.addEventListener('keypress', function() {

console.log(' I pressed press');

})

//2. keydown  It's triggered when the key is pressed   Can recognize function keys   such as  ctrl shift  Left and right arrows 

document.addEventListener('keydown', function() {

console.log(' I pressed down');

})

// 4.  The order of execution of the three events  keydown -- keypress -- keyup

</script>

</body>

7.9.1、 Keyboard object properties

Keyboard event object attribute explain
keyCode Returns the value of the key ASCII value

onkeydown and onkeyup Case insensitive ,onkeypress Case sensitive .

In our actual development , We use more keydown and keyup, It recognizes all the keys ( Including function keys )

Keypress The function key is not recognized , however keyCode Properties are case sensitive , Return to a different ASCII value

<body>

<script>

//  In the keyboard event object keyCode Property to get the corresponding key ASCII Code value 

// 1.  our keyup  and keydown Events are not case sensitive  a  and  A  All you get is 65

// 2.  our keypress  event   Case sensitive  a 97  and  A  Get is 65

document.addEventListener('keyup', function(e) {

console.log('up:' + e.keyCode);

//  We can use keycode Back to ASCII Code value to determine which key the user pressed 

if (e.keyCode === 65) {

alert(' You pressed a key ');

} else {

alert(' You did not press a key ')

}



})

document.addEventListener('keypress', function(e) {

console.log('press:' + e.keyCode);

})

</script>

</body>

 

原网站

版权声明
本文为[Cirrod]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131318484604.html