Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use DOM Technology in JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly analyzes the relevant knowledge points of how to use the DOM technology in JavaScript, the content is detailed and easy to understand, the operation details are reasonable, and has a certain reference value. If you are interested, you might as well follow the editor to have a look, and follow the editor to learn more about "how to use DOM technology in JavaScript".

1. Introduction to DOM 1.1.What is DOM

Document object Model (Document Object Model, DOM) is a standard programming interface recommended by W3C to deal with Extensible markup language (HTML or XML).

The W3C has defined a series of DOM interfaces that can change the content, structure and style of web pages through these DOM interfaces.

Document: a page is a document, which is represented by doucument in DOM

Elements: all tags on the page are elements, represented by element in DOM

Nodes: all content in a web page is a node (tags, attributes, text, comments, etc.), represented by node in DOM

DOM regards all of the above as objects.

2. Get element 2.1, how to get page element

DOM is mainly used to manipulate elements in our actual development.

How do we get the elements in the page?

You can get the elements in a page in the following ways:

Get according to ID

Obtain according to the label signature

Get through the new method of HTML5

Special element acquisition

2.2.According to ID

You can get an element object with ID using the getElementByld () method

Doucument.getElementByld ('id name')

Use console.dir () to print the element object we get and better view the properties and methods in the object.

Example

2019-9-9

/ / 1. Because our document page is loaded from top to bottom, we have to have a tag first, so script is written under the tag / / 2.get to get the element element by through hump nomenclature / / 3. The parameter id is a case-sensitive string / / 4. What is returned is an element object var timer = document.getElementById ('time'); console.log (timer); / / 5. Console.dir prints our element object to better view the properties and methods console.dir (timer) in it. 2.3.According to the tag signature

Based on the signature acquisition, you can use the getElementByTagName () method to return a collection of objects with the specified signature

Doucument.getElementsByTagName ('label signature')

Because what we get is a collection of objects, we need to traverse if we want to manipulate the elements in it.

Get that the element object is dynamic

What is returned is a collection of acquired element objects, which is stored as a pseudo-array

If the element cannot be obtained, an empty pseudo array is returned (because the object cannot be obtained)

Do you know it or not, it should be waiting for you for a long time. What is returned is that the collection of retrieved element objects is stored as a pseudo array of var lis = document.getElementsByTagName ('li'); console.log (lis); console.log (lis [0]); / / 2. Print and traverse for (var I = 0; I) in turn

< lis.length; i++) { console.log(lis[i]); } // 3.如果页面中只有 1 个 li,返回的还是伪数组的形式 // 4.如果页面中没有这个元素,返回的是空伪数组2.4、根据标签名获取 还可以根据标签名获取某个元素(父元素)内部所有指定标签名的子元素,获取的时候不包括父元素自己 element.getElementsByTagName('标签名')ol.getElementsByTagName('li'); 注意:父元素必须是单个对象(必须指明是哪一个元素对象),获取的时候不包括父元素自己 //element.getElementsByTagName('标签名'); 父元素必须是指定的单个元素 var ol = document.getElementById('ol'); console.log(ol.getElementsByTagName('li'));2.5、通过H5新增方法获取①getElementsByClassName 根据类名返回元素对象合集 document.getElementsByClassName('类名') document.getElementsByClassName('类名');②document.querySelector 根据指定选择器返回第一个元素对象 document.querySelector('选择器');// 切记里面的选择器需要加符号 // 类选择器.box // id选择器 #navvar firstBox = document.querySelector('.box');③document.querySelectorAll 根据指定选择器返回所有元素对象 document.querySelectorAll('选择器'); 注意 querySelector 和 querySelectorAll 里面的选择器需要加符号,比如: document.querySelector('#nav'); ④例子 // 1. getElementsByClassName 根据类名获得某些元素集合 var boxs = document.getElementsByClassName('box'); console.log(boxs); // 2. querySelector 返回指定选择器的第一个元素对象 切记 里面的选择器需要加符号 .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()返回指定选择器的所有元素对象集合 var allBox = document.querySelectorAll('.box'); console.log(allBox); var lis = document.querySelectorAll('li'); console.log(lis);2.6、获取特殊元素①获取body元素 返回body元素对象 document.body;②获取html元素 返回html元素对象 document.documentElement;3、事件基础3.1、事件概述 JavaScript 使我们有能力创建动态页面,而事件是可以被 JavaScript 侦测到的行为。 简单理解: 触发- 响应机制。 网页中的每个元素都可以产生某些可以触发 JavaScript 的事件,例如,我们可以在用户点击某按钮时产生一个事件,然后去执行某些操作。 3.2、事件三要素 事件源(谁) 事件类型(什么事件) 事件处理程序(做啥) // 点击一个按钮,弹出对话框 // 1. 事件是有三部分组成 事件源 事件类型 事件处理程序 我们也称为事件三要素 //(1) 事件源 事件被触发的对象 谁 按钮 var btn = document.getElementById('btn'); //(2) 事件类型 如何触发 什么事件 比如鼠标点击(onclick) 还是鼠标经过 还是键盘按下 //(3) 事件处理程序 通过一个函数赋值的方式 完成 btn.onclick = function() { alert('点秋香'); }3.3、执行事件的步骤 获取事件源 注册事件(绑定事件) 添加事件处理程序(采取函数赋值形式) // 执行事件步骤 // 点击p 控制台输出 我被选中了 // 1. 获取事件源 var p = document.querySelector('p'); // 2.绑定事件 注册事件 // p.onclick // 3.添加事件处理程序 p.onclick = function() { console.log('我被选中了'); }3.4、鼠标事件鼠标事件触发条件onclick鼠标点击左键触发onmouseover鼠标经过触发onmouseout鼠标离开触发onfocus获得鼠标焦点触发onblur失去鼠标焦点触发onmousemove鼠标移动触发onmouseup鼠标弹起触发onmousedown鼠标按下触发4、操作元素 JavaScript 的 DOM 操作可以改变网页内容、结构和样式,我们可以利用 DOM 操作元素来改变元素里面的内容 、属性等。注意以下都是属性 4.1、改变元素内容 从起始位置到终止位置的内容,但它去除html标签,同时空格和换行也会去掉。 element.innerText 起始位置到终止位置的全部内容,包括HTML标签,同时保留空格和换行 element[xss_clean] 我是文字 123 // innerText 和 innerHTML的区别 // 1. innerText 不识别html标签,去除空格和换行 var p = document.querySelector('p'); p.innerText = '今天是: 2019'; // 2. innerHTML 识别html标签 保留空格和换行的 p[xss_clean] = '今天是: 2019'; // 这两个属性是可读写的 可以获取元素里面的内容 var p = document.querySelector('p'); console.log(p.innerText); console.log(p[xss_clean]); 4.2、改变元素属性// img.属性img.src = "xxx";input.value = "xxx";input.type = "xxx";input.checked = "xxx";input.selected = true / false;input.disabled = true / false;4.3、改变样式属性 我们可以通过 JS 修改元素的大小、颜色、位置等样式。 行内样式操作 // element.stylep.style.backgroundColor = 'pink';p.style.width = '250px'; 类名样式操作 // element.className 注意: JS里面的样式采取驼峰命名法,比如 fontSize ,backgroundColor JS 修改 style 样式操作 ,产生的是行内样式,CSS权重比较高 如果样式修改较多,可以采取操作类名方式更改元素样式 class 因为是个保留字,因此使用className来操作元素类名属性 className 会直接更改元素的类名,会覆盖原先的类名 文本 // 1. 使用 element.style 获得修改元素样式 如果样式比较少 或者 功能简单的情况下使用 var test = document.querySelector('p'); test.onclick = function() { // this.style.backgroundColor = 'purple'; // this.style.color = '#fff'; // this.style.fontSize = '25px'; // this.style.marginTop = '100px'; // 让我们当前元素的类名改为了 change // 2. 我们可以通过 修改元素的className更改元素的样式 适合于样式较多或者功能复杂的情况 // 3. 如果想要保留原先的类名,我们可以这么做 多类名选择器 // this.className = 'change'; this.className = 'first change'; } 4.4、总结 4.5、排他思想 如果有同一组元素,我们相要某一个元素实现某种样式,需要用到循环的排他思想算法: 所有元素全部清除样式(干掉其他人) 给当前元素设置样式 (留下我自己) 注意顺序不能颠倒,首先干掉其他人,再设置自己 按钮1 按钮2 按钮3 按钮4 按钮5 // 1. 获取所有按钮元素 var btns = document.getElementsByTagName('button'); // btns得到的是伪数组 里面的每一个元素 btns[i] for (var i = 0; i < btns.length; i++) { btns[i].onclick = function() { // (1) 我们先把所有的按钮背景颜色去掉 干掉所有人 for (var i = 0; i < btns.length; i++) { btns[i].style.backgroundColor = ''; } // (2) 然后才让当前的元素背景颜色为pink 留下我自己 this.style.backgroundColor = 'pink'; } } //2. 首先先排除其他人,然后才设置自己的样式 这种排除其他人的思想我们成为排他思想

4.6, Custom attribute 4.6.1, get attribute value

Get the built-in attribute value (the attribute that comes with the element itself)

Element. Attribute

Get custom properties

Element.getAttribute ('attribute'); 4.6.2, set property value

Set built-in property values

Element. Attribute = 'value'

Mainly set custom properties

Element.setAttribute ('attribute'); 4.6.3. Remove attribute element.removeAttribute ('attribute')

Var p = document.querySelector ('p'); / / 1. Get the attribute value of the element / / (1) element. Attribute console.log (p.id); / / (2) element.getAttribute ('attribute') get gets the meaning of getting the attribute attribute that we programmers add ourselves we call the custom attribute index console.log (p.getAttribute ('attribute)); console.log (p.getAttribute (' index')); / / 2. Set the element attribute value / / (1) element. Attribute = 'value' p.id = 'test'; p.className =' navs'; / / (2) element.setAttribute ('attribute', 'value'); mainly for custom attributes p.setAttribute ('value 2); p.setAttribute (' class', 'footer') / / class is special. What is written here is that class is not className / / 3 remove attributes removeAttribute (attributes) p.removeAttribute ('index'); 4.7, H5 custom attributes

Custom attribute purpose:

Save and save data, some data can be saved to the page without having to save to the database

Some custom attributes can easily cause ambiguity, and it is not easy to judge whether they are built-in attributes or custom attributes, so H5 has a stipulation.

2.8.1 set H5 custom properties

H5 specifies that the custom attribute data- begins as the attribute name and assigns a value

/ / or use JavaScript to set p.setAttribute ('data-index',1); 2.8.2 get H5 custom attributes

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

New to H5: element.dataset.index or element.dataset ['index'] IE11 is only supported.

Var p = document.querySelector ('p'); console.log (p.getAttribute ('getTime')); p.setAttribute (' data-time', 20); console.log (p.getAttribute ('data-index')); console.log (p.getAttribute (' data-list-name')) / / H6 added method to get custom attributes it can only get the dataset that begins with data- / / dataset is a collection that stores all custom attributes that begin with data console.log (p.dataset); console.log (p.dataset.index); console.log (p.dataset ['index']) / / if there are multiple-linked words in the custom attribute, we use the hump naming method console.log (p.dataset.listName); console.log (p.dataset ['listName']); 5. Node operation

Elements are usually obtained in two ways:

1. Use the method provided by DOM to get element 2. Using the node hierarchy relationship to obtain the element document.getElementById () using the parent-son-brother node relationship to obtain the element document.getElementsByTagName () is logical, but the compatibility is poor, document.querySelector and so on.

It is not logical and tedious.

Both of these methods can get the element node, which we will use later, but the node operation is easier.

In general, a node has at least three basic attributes

5.1. Node Overview

Everything in a web page is a node (tags, attributes, text, comments, etc.). In DOM, nodes are represented by node.

All nodes in the HTML DOM tree are accessible through JavaScript, and all HTML elements (nodes) can be modified, created or deleted.

In general, a node has at least three basic attributes: nodeType (node type), nodeName (node name), and nodeValue (node value).

Element node: nodeType is 1

Attribute node: nodeType is 2

Text node: nodeType is 3 (text node includes text, spaces, line feeds, etc.)

In our actual development, the main operation of node operation is element node.

Nodes can be divided into different hierarchical relationships by using DOM tree, and the common hierarchical relationship is father-son-brother relationship.

5.2. parent node Node [XSS _ clean]

The parentNode attribute can return the parent node of a node, note that it is the nearest parent node

Returns null if the specified node does not have a parent node

I'm p.

I'm span. I'm li. I'm li.

/ / 1. Parent node parentNode var erweima = document.querySelector ('.erweima'); / / var box = document.querySelector ('.box'); / / the parent node closest to the element (parent) is returned as null console.log (erweima [XSS _ clean]) if the parent node is not found; 5.3. child node parentNode.childNodes (standard)

ParentNode.childNodes returns a collection of child nodes of the specified node, which is an instantly updated collection

The return value contains all the child nodes, including element nodes, text nodes, etc.

If you only want to get the element nodes inside, you need to deal with it specially. Therefore, we generally do not advocate the use of childNodes

ParentNode.children (non-standard)

ParentNode.children is a read-only attribute that returns all child element nodes

It only returns child element nodes, and the rest of the nodes do not return (this is what we focus on)

Although children is a non-standard, it is supported by various browsers, so we can safely use it.

I'm li, I'm li / / the method provided by DOM (API), get var ul = document.querySelector ('ul'); var lis = ul.querySelectorAll (' li'); / / 1. Child node childNodes all child nodes include element node text node and so on console.log (ul.childNodes); console.log (ul.childNodes [0] .nodeType); console.log (ul.childNodes [1] .nodeType); / / 2. Children to get all the child element nodes is also the console.log (ul.children) commonly used in our actual development. 5.3.1. ParentNode.firstChild of the first child node

FirstChild returns the first child node, and null if it cannot be found

Similarly, it also includes all nodes.

5.3.2, the last child node parentNode.lastChild

LastChild returns the last child node, or null if it is not found.

Similarly, it also includes all nodes.

I am li1, I am li2, I am li3, I am li4, I am li5 var ol = document.querySelector ('ol'); / / 1. The first child node of firstChild, whether it is a text node or an element node, console.log (ol.firstChild); console.log (ol.lastChild) / / 2. FirstElementChild returns the first child element node ie9 to support console.log (ol.firstElementChild); console.log (ol.lastElementChild); / / 3. The actual developed method does not have compatibility problems and returns the first child element console.log (ol.children [0]); / / the first child element node console.log (ol.children.children.length-1]); / / the last child element node

5.3.3. First child node (compatibility) parentNode.firstElementChild

FirstElementChild returns the first child node, and null if it cannot be found

If there is a compatibility problem, only support it above IE9.

5.3.4. Last child node (compatibility) parentNode.lastElementChild

LastElementChild returns the last child node, or null if it is not found.

If there is a compatibility problem, only support it above IE9.

5.3.5, solution

In actual development, firstChild and lastChild contain other nodes, which are inconvenient to operate, and firstElementChild and lastElementChild have compatibility problems, so how do we get the first or last child element node?

Solution

If you want the first child element node, you can use parentNode.chilren [0]

If you want the last child element node, you can use the

/ / the number of elements in the array minus 1 is the index number of the last element parentNode.chilren [parentNode.chilren.length-1]

Example:

I'm li1, I'm li2, I'm li3, I'm li4 var ol = document.querySelector ('ol'); / / 1.firstChild gets the first child node, including the text node and the element node console.log (ol.firstChild); / / returns the text node # text (the first newline node) console.log (ol.lastChild) / / return the text node # text (the last newline node) / / 2. FirstElementChild returns the first child element node console.log (ol.firstElementChild); / / I am li1 / / the second method has a compatibility problem and needs more than IE9 to support / / 3. In actual development, there is no compatibility problem, and the first child element console.log (ol.children [0]) is returned; / / I am li1 console.log (ol.children [3]); / / I am li4 / / when there is not a unique number of li in it, so write console.log (ol.children.children.length-1] when the last node is needed. 5.4.1sibling node, node.nextSibling, next sibling node.

NextSibling returns the next sibling node of the current element, or null if it is not found

Similarly, it also includes all nodes.

5.4.2, previous sibling node node.previousSibling

PreviousSibling returns a sibling element node on the current element, or null if it is not found

Similarly, it also includes all nodes.

5.4.3, next sibling node (compatibility) node.nextElementSibling

NextElementSibling returns the next sibling node of the current element, or null if it is not found

IE9 supports it only if there are compatibility problems.

5.4.4, previous sibling node (compatibility) node.previousElementSibling

PreviousElementSibling returns a sibling element node on the current element, or null if it is not found

IE9 supports it only if there are compatibility problems.

Example

I'm p.

I am span var p = document.querySelector ('p'); / / the next sibling node of 1.nextSibling contains element nodes or text nodes and so on console.log (p.nextSibling); / / # text console.log (p.previousSibling); / / # text / / 2. NextElementSibling gets the next sibling element node console.log (p.nextElementSibling) / / I am span console.log (p.previousElementSibling); / / null

How to solve the compatibility problem?

Answer: encapsulate a compatibility function by yourself

Function getNextElementSibling (element) {var el = element; while (el = el.nextSibling) {if (el.nodeType = 1) {return el;}} return null;} 5.5, create node document.createElement ('tagName')

The document.createElement () method creates the HTML element specified by tagName

Because these elements do not exist before and are generated dynamically according to our requirements, we also call them dynamic element nodes.

5.5.1. Add node node.appendChild (child)

The node.appendChild () method adds a node to the end of the list of child nodes of the specified parent node. Similar to the after pseudo-element in CSS.

Node.insertBefore (child, specified element)

The node.insertBefore () method adds a node before the specified child node of the parent node. Similar to the before pseudo-element in CSS.

Example

123 / / 1. Create the node element node var li = document.createElement ('li'); / / 2. Add node node.appendChild (child) node parent child is a child append element similar to push / / get parent ul var ul = document.querySelector ('ul'); ul.appendChild (li); / / 3 in the array. Add node node.insertBefore (child, specified element); 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 element 2. Add element 5.5.2, delete node node.removeChild (child)

The node.removeChild () method deletes a child node from the DOM and returns the deleted node.

5.5.3. Replication node (clone node) node.cloneNode ()

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

If the parenthesis parameter is empty or false, it is a shallow copy, that is, only the replication node itself is cloned, and the child nodes are not cloned.

If the parenthesis parameter is true, it is a deep copy, which copies the node itself and all the child nodes in it.

Example

1111 2 3 var ul = document.querySelector ('ul'); / / 1. Node.cloneNode (); empty brackets or false shallow copy inside only copy the contents of the tag / / 2. Node.cloneNode (true); parentheses are true deep copy copy tag copy contents var lili = ul.children [0] .cloneNode (true) Ul.appendChild (lili)

5.5.4, interview questions

The difference between three dynamic creation elements

Doucument.write ()

Element[xss _ clean]

Document.createElement ()

Difference:

[xss_clean] () is a content stream that writes content directly to the page, but when the document flow is finished, it will cause the page to be completely redrawn.

InnerHTML writes content to a DOM node and does not cause the page to be completely redrawn

InnerHTML is more efficient in creating multiple elements (instead of concatenating strings, stitching in array form), and the structure is slightly more complex.

/ / 2. InnerHTML creates the element var inner = document.querySelector ('.inner'); / / 2.1 innerHTML uses the concatenation string method for (var I = 0; I html-> body-> father-> son)

Two boxes are nested, one parent box and one child box. Our requirement is to pop up father when clicking on the parent box and son when clicking on the child box

Son box

/ / there are three phases in the dom event flow / / 1. Only one of these phases can be captured or bubbled in JS code. / / 2. Onclick and attachEvent (ie) can only get the bubbling phase. / / 3. Capture phase if the third parameter of addEventListener is true, then it is in capture phase document-> html-> body-> father-> son var son = document.querySelector ('.son'); son.addEventListener ('click', function () {alert (' son');}, true); var father = document.querySelector ('.capture') Father.addEventListener ('click', function () {alert (' father');}, true)

But because of the influence of the DOM stream, if we click on the subbox, the father will pop up first, and then the son will pop up.

This is because the capture phase starts with the top node of the DOM and then propagates down step by step to the most specific element receiving

Document-> html-> body-> father-> son

First look at the document event, no; then look at the html event, no; then look at the body event, no; then look at the father event, execute first; then look at the son event, and then execute.

7.3.2, bubbling stage

Son-> father-> body-> html-> document

Son box

/ / 4. In bubbling stage, if the third parameter of addEventListener is false or omitted, then it is in bubbling stage son-> father-> body-> html-> document var son = document.querySelector ('.son'); son.addEventListener ('click', function () {alert (' son');}, false); var father = document.querySelector ('.bubble') Father.addEventListener ('click', function () {alert (' father');}, false); document.addEventListener ('click', function () {alert (' document');})

When we click on the subbox, son, father, and document will pop up.

This is because the bubbling phase is received by the most specific element at the beginning, and then propagated up to the top node of the DOM.

Son-> father-> body-> html-> document

7.3.3. Summary

Only one of the stages of capturing or bubbling can be performed in JS code

Onclick and attachEvent can only get the bubble phase.

The third parameter of addEventListener (type,listener [, useCapture]), if true, indicates that the event handler is called during the event capture phase; if false (default is false, if not written), the event handler is called during the event bubbling phase.

We rarely use event capture in actual development, and we pay more attention to event bubbling.

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

EventTarget.onclick = function (event) {/ / this event is the event object, which we like to write as e or evt} eventTarget.addEventListener ('click', function (event) {/ / this event is the event object, and we also like to write it as e or evt})

Official explanation: the event object represents the state of the event, such as the state of the keyboard button, the position of the mouse, and the state of the mouse button

Simple understanding:

Who bound this event?

If the mouse triggers the event, you will get the relevant information about the mouse, such as the location of the mouse

If the keyboard triggers the event, you will get information about the keyboard, such as which key was pressed.

After the event, a collection of information and data related to the event is put into this object

This object is the event object event, which has many properties and methods, such as "

This event is a parameter, and the system sets it as the event object for us. There is no need to pass the actual parameter to the past.

When we register the event, the event object is automatically created by the system and passed to the event listener (event handler).

one hundred and twenty three

/ / event object var p = document.querySelector ('p'); p.onclick = function (e) {/ / console.log (e); / / console.log (window.event); / / e = e | | window.event; console.log (e) } / / 1. Event is an event object written in parentheses of our listening function as a parameter to see / / 2. The event object exists only when there is an event. It is automatically created for us by the system. There is no need for us to pass the parameter / / 3. The event object is a collection of a series of data related to our events, such as mouse clicks, which contain mouse-related information, mouse coordinates, ah, if it is a keyboard event, it contains information about keyboard events, such as judging which key the user pressed / / 4. We can name this event object ourselves, such as event, evt, e / / 5. Event object also has compatibility problems ie678 is written as e = e through window.event compatibility | | window.event; 7.4.1, compatibility scheme of event object

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

In the standard browser, the parameters passed to the method by the browser can be obtained by defining the formal parameter e.

In IE6~8, the browser does not pass parameters to the method. If necessary, you need to go to the window.event to get the lookup.

Resolve:

E = e | | window.event 7.4.2. Common properties of event objects and methods event object properties method description e.target returns the object that triggers the event standard e.srcElement returns the object that triggers the event non-standard ie6-8 uses e.type to return the type of event such as click mouseover without one.cancelBubble this property prevents bubbling, non-standard, ie6-8 uses e.returnValue to prevent the default behavior from being non-standard Ie6-8 uses e.preventDefault (), which blocks default behavior standards such as do not let links jump to e.stopPropagation () to prevent bubbling.

The difference between e.target and this:

This is the element of the event binding, the caller of this function (the element that binds the event)

The e.target is the element that triggers the event.

7.5. Event object blocks default behavior

one hundred and twenty three

Baidu / / attributes and methods of common event objects / / 1. Returns the event type var p = document.querySelector ('p'); p.addEventListener ('click', fn); p.addEventListener (' mouseover', fn); p.addEventListener ('mouseout', fn); function fn (e) {console.log (e.type);} / / 2. Block the default behavior (event) so that the link does not jump or the submit button does not submit var a = document.querySelector ('a'); a.addEventListener ('click', function (e) {e.preventDefault (); / / dom standard writing}) / / 3. The traditional registration method a.onclick = function (e) {/ / ordinary browser e.preventDefault (); method / / e.preventDefault (); / / lower version browser ie678 returnValue attribute / / e.returnValue / / We can also use return false to prevent the default behavior from having no compatibility problems: the code behind return is not executed and is limited to the traditional registration method return false; alert (11).

Event bubbling: initially received by the most specific element, and then propagated up to the top node of the DOM

The characteristics of event bubbling itself, the disadvantages and benefits that will be brought by the event, need us to grasp flexibly.

Standard writing method

E.stopPropagation ()

Non-standard writing: IE6-8 makes use of the object event cancelBubble attribute

E.cancelBubble = true; son son

/ / attributes and methods of common event objects / / stop bubbling dom recommended standard stopPropagation () var son = document.querySelector ('.son'); son.addEventListener ('click', function (e) {alert (' son'); e.stopPropagation (); / / stop stops Propagation propagation e.cancelBubble = true / / non-standard cancel cancel bubble bubble}, false); var father = document.querySelector ('.bubble'); father.addEventListener ('click', function () {alert (' father');}, false); document.addEventListener ('click', function () {alert (' document')) 7.6.1, compatibility solution to prevent event bubbling if (e & & e.stopPropagation) {e.stopPropagation ();} else {window.event.cancelBubble = true;} 4.4.4 e.target and this

The difference between e.target and this

This is the element of the event binding, the caller of this function (the element that binds the event)

E.target is the element that triggers the event

one hundred and twenty three

Abc / / attributes and methods of common event objects / / 1. E.target returns the object that triggers the event (element) this returns the object (element) of the binding event / / difference: when e.target clicks on that element, it returns that element this that element binds the click event Then return who var p = document.querySelector ('p') P.addEventListener ('click', function (e) {console.log (e.target); console.log (this);}) var ul = document.querySelector (' ul'); ul.addEventListener ('click', function (e) {/ / We bind events to ul so this points to ul console.log (this) Console.log (e.currentTarget); / / e.target points to the object we clicked on who triggered this event. When we click on li e.target, we point to li console.log (e.target). }) / / understand compatibility / / p.onclick = function (e) {/ / e = e | | window.event; / / var target = e.target | | e.srcElement; / / console.log (target); / /} / / 2. Understand that there is a very similar property to this currentTarget ie678 does not recognize the compatibility of 4.4.5 event objects

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

In a standard browser, the browser is the parameter passed to the method, which can be obtained by defining the formal parameter e.

In IE6-> 8, the browser does not pass parameters to the method. If necessary, you need to go to window.event to get the lookup.

Solution

E = e | | window.event

one hundred and twenty three

/ / event object var p = document.querySelector ('p'); p.onclick = function (e) {/ / e = e | | window.event; console.log (e); / / event object also has compatibility problems. Ie678 is written by window.event compatibility e = e | | window.event } 7.7. Event delegation

Event delegate is also called event proxy, which is called event delegate in jQuery.

The principle of event delegation

Instead of setting event listeners on each child node individually, event listeners are set on its parent node, and then use the bubbling principle to influence the setting of each child node

Do you know if I should have a bullet box in my hand? Do you know if I should have a bullet box in my hand? Do you know if I should have a bullet box in my hand? Do you know if I should have a bullet box in my hand? Do you know if I should have a bullet box in my hand? / / the core principle of event delegation: add listeners to the parent node and use event bubbles to affect each child node var ul = document.querySelector ('ul'); ul.addEventListener (' click', function (e) {/ / alert ('do you know, I should have a bullet box in hand!') ; / / e.target, you can get the object we clicked on e.target.style.backgroundColor = 'pink'; / / change the backgroundColor color in the style to pink})

The above case: register the click event to the ul, and then use the target of the event object to find the currently clicked li, because if you click li, the event will bubble on the ul, and if the ul has a registered event, the event listener will be triggered.

Onclick mouse click left button triggers onmouseover mouse passing through triggering onmouseout mouse leaving triggering onfocus to get mouse focus triggering onblur losing mouse focus triggering onmousemove mouse movement triggering onmousedown mouse down triggering 7.8.1, disabling right mouse button and mouse selection

Contextmenu mainly controls when the context menu should be displayed, mainly for programmers to cancel the default context menu

Selectstart disables mouse selection

I am a text that I do not want to share / / 1. Contextmenu We can disable the right-click menu document.addEventListener ('contextmenu', function (e) {e.preventDefault (); / / block default behavior}) / / 2. Disable the text selectstart document.addEventListener ('selectstart', function (e) {e.preventDefault ();}) 7.8.2. Mouse event object

The event object represents the state of the event, a collection of information related to the event.

At present, we mainly use mouse event object MouseEvent and keyboard event object KeyboardEvent.

Mouse event object description e.clientX returns the X coordinate of the mouse relative to the visual area of the browser window e.clientY returns the Y coordinate of the mouse relative to the visual area of the browser window e.pageX (emphasis) returns the X coordinate of the mouse relative to the document page IE9+ supports e.pageY (emphasis) returns the Y coordinate of the mouse relative to the document page IE9+ supports e.screenX to return the X coordinate of the mouse relative to the computer screen E.screenY returns the Y coordinate of the mouse relative to the computer screen / / the mouse event object MouseEvent document.addEventListener ('click' Function (e) {/ / 1. The x and y coordinates of the client mouse in the visual area console.log (e.clientX) Console.log (e.clientY); console.log ('-'); / / 2. Page mouse in the x and y coordinates of the document console.log (e.pageX); console.log (e.pageY) Console.log ('-'); / / 3. Screen the x and y coordinates of the mouse on the computer screen console.log (e.screenX); console.log (e.screenY) Commonly used keyboard event keyboard event trigger condition onkeyup when a keyboard key is released trigger onkeydown when a keyboard key is pressed trigger onkeypress when a keyboard key is pressed, but it does not recognize function keys, such as ctrl shift arrows, etc.

If you use addEventListener, you do not need to add on

The difference between onkeypress and the previous two is that it does not recognize function keys, such as left and right arrows, shift, etc.

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

/ / commonly used keyboard events / / 1. Trigger when keyup key pops up / / _ document.onkeyup = function () {/ / console.log ('I'm up'); / /} document.addEventListener ('keyup', function () {console.log (' I'm up') }) / / 3. Unrecognized function keys are triggered when the keypress key is pressed, such as the ctrl shift left and right arrow, document.addEventListener ('keypress', function () {console.log (' I pressed press') }) / / 2. When the keydown key is pressed, it triggers the recognition function key such as ctrl shift left and right arrow document.addEventListener ('keydown', function () {console.log (' I pressed down');}) / / 4. The execution order of the three events keydown-- keypress-- keyup 7.9.1. Keyboard object Properties Keyboard event object property indicates that keyCode returns the ASCII value of the key value.

Onkeydown and onkeyup are not case-sensitive, while onkeypress is case-sensitive.

In our actual development, we use keydown and keyup more, which can recognize all keys (including function keys).

Keypress does not recognize function keys, but keyCode is case-sensitive and returns different ASCII values

/ / the keyCode attribute in the keyboard event object can get the ASCII code value of the corresponding key / / 1. Our keyup and keydown events are case-insensitive and get 65 / / 2 for both An and A. Our keypress event case sensitive a 97 and A yields 65 document.addEventListener ('keyup', function (e) {console.log (' up:' + e.keyCode); / / We can use the ASCII code value returned by keycode to determine which key the user pressed if (e.keyCode = = 65) {alert ('your pressed a key') } else {alert ('you didn't press a key')}) document.addEventListener ('keypress', function (e) {console.log (' press:' + e.keyCode);}) what is the role of JavaScript 1, can embed dynamic text in HTML pages. 2. Respond to browser events. 3. Read and write HTML elements. 4. Verify the data before it is submitted to the server. 5. Detect the browser information of visitors. 6. Control cookies, including creation and modification, etc. 7. Server-side programming based on Node.js technology.

About "how to use DOM technology in JavaScript" is introduced here, more related content can be searched for previous articles, hope to help you answer questions, please support the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report