DOM of JavaScript Advanced Web APl Notes

Table of contents

1. What is Web API

Two, DOM

DOM object

Three, DOM element acquisition

4. Operating elements

4.1. Modify element content

4.2. Setting/Modifying Element Attributes

4.3. Setting/Modifying Style Attributes

4.4. Custom attributes

get attribute value

set attribute value

Five, node node

5.1. Parent and child nodes:

5.2. Brother nodes

5.3. Create, add, delete, and copy nodes

The difference between the three dynamically created elements

6. Events

6.1. Three elements of the event:

6.2. Steps to execute the event

6.3, registration event

1. Registration method

2. Delete event (unbind event)

6.4, DOM event flow

6.5, event object

Common Properties and Methods of Event Objects

6.6. Event delegation

6.7, event type

6.7.1 Mouse events and their objects

6.7.2 Keyboard events and their objects

Seven, DOM summary


1. What is Web API

APl: application programming interface, which is some predefined functions, the purpose is to achieve certain functions, and there is no need to know its internal implementation details.
Simply put, if you want to use the API well, you only need to understand what the API interface does and what it returns

WebAPI is a set of interfaces provided by the browser for operating web pages, allowing users to easily operate the elements of the page and some functions of the browser.
Web APIs = DOM Document Object Model (change content, structure and style of web pages) + BOM Browser Object Model (interact with browser window independently of content)

Here mainly introduces the DOM document object model

Two, DOM

insert image description here

DOM tree: The HTML document is displayed intuitively in a tree structure, which is called a document tree or a DOM tree. The document tree intuitively reflects the relationship between tags.

DOM object

DOM object: The JS object generated by the browser according to the html tag, regards all the contents in the DOM tree as objects.
Document: A page is a document, which is represented by doucument in DOM
Element: All tags in the page are elements, and element is used in DOM to represent
nodes: All content in a web page is a node (label, attribute, text, comment, etc.) , DOM uses node to represent
features
1. All label properties can be found on this object
2. Modifying the properties of this object will automatically map to the label

Three, DOM element acquisition

method of obtaining grammar parameter return
get by id doucument.getElementByld() id name element object
Get by tag name doucument.getElementsByTagName() tag name A collection of element objects, stored in the form of a pseudo-array, if it does not exist, return a pseudo-array with a length of 0
HTML5 new method to get ①document.getElementsByClassName()
② document.querySelector()
③document.querySelectorAll()
① class name
② css selector
③ css selector
① A collection of element objects, stored in the form of a pseudo-array.
② The first element matched by the CSS selector, an HTMLElement object. If no match is found, null will be returned.
③ A collection of NodeList objects matched by the CSS selector, which is a pseudo-array

Get special elements:
get body object: document.body;
get html element: document.documentElement;

4. Operating elements

4.1. Modify element content

document.write()
1. Only the text content can be appended to the previous position (creation)
2. The label contained in the text will be parsed by
the innerText attribute of the element
1. Add or update the text content to the position of any label
2. The text contains The tags will not be parsed, and
the innerHTML attribute of the blank and newline element will not be preserved.
1. Add/update the text content to any tag position.
2. The tags contained in the text will be parsed, and the blank and newline will be preserved.

Code example:

<body>
   <P>段落一</P>
   <p id="pp">段落二</p>
<script>
    document.write('好好学习,天天向上');
    // 里面的标签会被解析
    document.write('<h2>学习令人兴奋</h2>');
    var one=document.querySelector('p')
    one.onclick=function(){
        one.innerText='<h1>段落 三</h1>'  
    }
    var two=document.getElementById('pp')
    two.onclick=function(){
        two.innerHTML='<h1>段落 三</h1>'
    }
</script>
</body>

 Effect :

4.2. Setting/Modifying Element Attributes

Small case: show/hide password input

Effect:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo</title>
    <style>
        .box {
            position: relative;
            width: 200px;
            border-bottom: 1px solid #ccc;
            margin: 100px auto;
        }
        .box input {
            width: 370px;
            height: 30px;
            border: 0;
            outline: none;
        }
        .box img {
            position: absolute;
            top: 10px;
            right: 30px;
            width: 24px;
        }
    </style>
</head>
<div class="box">
    <label for=""><img src="图片地址" id="eye"> </label>
    <input type="password" name="" id="pwd">
</div>
<script>
    var eye = document.getElementById('eye');
        var pwd = document.getElementById('pwd');
        var flag = 0;
        eye.onclick = function () {
            if (flag == 0) {
                pwd.type = 'text';
                eye.src = '';
                flag = 1;
            } else {
                pwd.type = 'password';
                eye.src = '';
                flag = 0;
            }
 
        }
</script>
</body>
</html>

The attributes of each tag element can be accessed through "."

4.3. Setting/Modifying Style Attributes

We can modify the size, color, position and other styles of elements through JS.

method example

via the style attribute

div.style.backgroundColor = 'pink';
div.style.width = '250px';

By class name className

.change{ width:30px; height:30px; }
//Change the class name of the current element to change
//className will overwrite the original class name
this.className = 'change';

//Retain the original class name
this.className = 'previous change';

by classList

//In order to solve the problem that className is easy to overwrite the previous class name, we can add and delete class names through classList

element.classList.add('class name') //add
element.classList.remove('class name') //remove
element.classList.toggle('class name') // switch

Small case: Realize the text prompt function of the input box

<input type="text" value="请输入账号" style="width: 200px; height:30px; outline: none; color: rgb(201, 189, 189);;">
<script>
    var inp = document.querySelector('input');
    inp.onfocus = function () {
        if (this.value == '请输入账号') {
            this.value = '';
            this.style.color = 'black'
        }
    }
    inp.onblur = function () {
        if (this.value == '') {
            this.value = '请输入账号'
            this.style.color = 'rgb(201, 189, 189)'
        }
    }
</script>

Exclusive thought

If there is a set of styles, and we want a certain element to achieve a certain style, we need to use the exclusive thinking algorithm of the cycle:

1. All elements clear styles (kill others)

2. Style the current element (leave me alone)

3. Note that the order cannot be reversed, kill other people first, and then leave myself

</head>
<button>11</button>
<button>22</button>
<button>33</button>
<script>
    //1.获取所有的元素
    var btns = document.getElementsByTagName('button');
    //btns得到的是伪数组,里面的每一个元素btn[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';
        }
    }
</script>
</body>
</html>

4.4. Custom attributes

Purpose: To save and save data, some data can be saved to the page instead of to the database.
Some custom attributes are easy to cause ambiguity, and it is not easy to judge whether it is a built-in attribute or a custom one, so H5 has stipulated custom attributes to data-beginning

get attribute value

Get built-in attribute values ​​(attributes that come with the element itself): Get custom attributes:element.属性;
element.getAttribute('属性');

set attribute value

Set built-in property values: mainly set custom properties:element.属性 = '值';
element.setAttribute('属性','值');

Five, node node

All content in a web page is a node node (label, attribute, text, comment, etc.), and the DOM tree can be used to divide nodes into different hierarchical relationships. The common ones are parent, child, brother, and hierarchical relationships. In actual development, node operations mainly operate element nodes, which are relatively simple and logical, but slightly less compatible.

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

5.1. Parent and child nodes:

// parent node

node.parentNode: Return the parent node of a node, pay attention to the nearest parent node, if the specified node has no parent node, return null

// child node

parentNode.children : is a read-only property that returns all child element nodes, and the rest of the nodes do not return, (important) (non-standard--but widely used)
parentNode.firstChild : returns the first child node, whether it is a text node or an element Node, return null if there is no
parentNode.lastChild : return the last child node, whether it is a text node or an element node, return null if there is no
parentNode.firstElementChild : is a read-only property, only return the first child node, return null if there is no , IE9 and above only support
parentNode.lastElementChild : it is a read-only property that only returns the last child node, and returns null if there is no one. IE9 and above only support
//writing in actual development, there is no compatibility problem, and the element
parentNode can be returned .children[0]
parentNode.children[parentNode.children.length-1]

What are read-only properties:

For example: if <div> <!--a--><img src='' ''> </div> in the html page

parentNode.firstElementChild returns <img src='' ''> 

parentNode.firstChild returns <!--a-->, because text nodes and comment nodes are also counted as child nodes

5.2. Brother nodes

nextSibling returns the next sibling element node of the current element, including element nodes and text nodes, and returns null if not found.

previousSibling returns the previous sibling element node of the current element, including element nodes and text nodes, and returns null if it cannot be found

nextElementSibling returns the next sibling element node of the current element, or null if not found. Compatibility, IE 9+

previousElementSibling returns the previous sibling element node of the current element, or returns null if not found. Compatibility, IE 9+

5.3. Create, add, delete, and copy nodes

To add a new element to the page, you need to create the element first and then add it

1. Create a node
document.createElement('tagName')
Because these elements did not exist before, they are dynamically generated according to the requirements, so it is also called dynamically creating element nodes
2. Add a node
node.appendChild(child)    method to add a node to Specifies the end of the parent node's list of child nodes. Similar to the after pseudo-element in CSS.
The node.insertBefore(child, specified element)    method adds a node to the front of the specified child node of the parent node. Similar to the before pseudo-element in CSS.

3. Delete node

The node.removeChild(child)    method removes a child node from the DOM and returns the removed node

4. Duplicate node

The node.cloneNode()   method returns a copy of the node on which the method was called.

If the parentheses are false (default), it is a shallow copy, that is, only the copied node itself is cloned, and the child nodes inside are not cloned.
If the parentheses parameter is true, it is a deep copy, which will copy the node itself and all its child nodes

The difference between the three dynamically created elements

1.document.write()
   document.write('<div>123</div>')
   directly writes the content into the content flow of the page, but the document flow is executed, so it will cause all pages to be redrawn, that is to say, If the page document flow is loaded, the original one will be gone
2. element.innerHTML
   element.innerHTML = '<a> create tag</a>'
  features:
  (1) innerHTML is to write the content into a certain DOM node, ** It will not cause page redraw**
  (2) innerHTML is more efficient to create multiple elements (but do not use the form of splicing strings, it is efficient to use array splicing)
3.document.createElement()
 Features: When creating a large number of elements, A little less efficient, but the structure is clearer

6. Events

Events are behaviors that can be detected by JavaScript, such as keyboard operations and mouse operations. Simple understanding: trigger-response mechanism

6.1. Three elements of the event:

    事件源 :事件被触发的对象 谁 按钮
    事件类型 如何触发,什么事件,比如鼠标点击,还是鼠标经过
    事件处理程序:通过一个函数赋值的方式完成

6.2. Steps to execute the event

  1. get event source
  2. Register event (binding event)
  3. Add event handlers (in the form of function assignments)

6.3, registration event

1. Registration method

Adding events to elements is called registering events or binding events. There are two ways to register events: the traditional method and the event monitoring registration method.
The traditional method
btn.onclick = function() { }
Features: the uniqueness of registered events
The same element and the same event can only set one handler function, and the last registered handler function Will override the previously registered handler function.

Event monitoring registration method -- -----w3c recommended method, the same element and the same event can register multiple listeners, and they will be executed sequentially according to the registration order.
1. eventTarget.addEventListener(type,listener[,useCapture])

  • type: event type string, such as click, mouseover, be careful not to bring on here
  • listener: event processing function, when the event occurs, the listening function will be called
  • useCapture: optional parameter, is a boolean value, the default is false. After reading the DOM event stream, learn more about

2.eventTarget.attachEvent(eventNameWithOn, callback)

  • eventNameWithOn: event class string, onclick, onmouseover, here with on
  • callback: event processing function, the callback function is called when the target touches the event.

2. Delete event (unbind event)

The traditional method
eventTarget.onclick = null
event listening method

  • eventTarget.removeEventListener(type,listener[,useCapture]);
  • eventTarget.detachEvent(eventNameWithOn, callback); used together with attachEvent

6.4, DOM event flow

The event flow describes the order in which events are received from the page. When an event occurs, it will be propagated among the element nodes in a specific order. This propagation process is the DOM event flow event bubbling: IE was first proposed, and the event is started by the
most specific The element is received, and then propagated up to the topmost node of the DOM step by step. Bottom-up
event capture : Netscape first proposed that it starts from the topmost node of the DOM, and then propagates down to the most specific element receiving process.      From top to bottom

 Event bubbling:
1. When an event of an element is triggered, the same event (event with the same name) will be triggered sequentially in all ancestor elements of the element. This process is called event bubbling.
2. Event bubbling exists by default. If you want to limit the event to the current element, you need to stop the flow of events. To stop the flow of events, you need to get the event object.

Notice:

  1. Only one phase of capturing or bubbling can be executed in js
  2. onclick and attachEvent can only get the bubbling phase
  3. If the third parameter of addEventListener(type,listener[,useCapture]) is true: it means that the event handler is called during the event capture phase; false (not written/default): it means that the event handler is called during the event bubbling phase

Prevent bubbling
e.stopPropagation();
e.cancelBubble = true;
If the child element prevents the event from bubbling, the parent element and the grandparent element will not respond, but at this time, if the parent element triggers the event, the grandparent element will still have react

6.5, event object

// 这个 event 就是事件对象,我们还喜欢的写成 e 或者 evt 
eventTarget.onclick = function(event) {} 

 1. event 就是一个事件对象 事件绑定的回调函数的第一个参数就是 事件对象
 2. 事件对象只有有了事件才会存在,它是系统给我们自动创建的,不需要我们传递参数
 3. 事件对象 是 我们事件的一系列相关数据的集合 跟事件相关的 比如鼠标点击里面就包含了鼠标的相关信息,鼠标坐标啊,如果是键盘事件里面就包含的键盘事件的信息 比如 判断用户按下了那个键
 4. 这个事件对象我们可以自己命名 比如 event 、 evt、 e
 5. 事件对象也有兼容性问题 ie678 通过 window.event 兼容性的写法  e = e || window.event;

Official explanation: the event object represents the state of the event, such as the state of the keyboard key, the position of the mouse, and the state of the mouse button. Simple understanding
: after the event occurs, a series of events related to the event are triggered. The relevant information collection is placed in this event object event; it has many properties and methods

Common Properties and Methods of Event Objects

Event object property method illustrate
e.target Returns the object criteria that triggered the event
e.type Return the type of event such as click mouseover without on
e.preventDefault() This method prevents the default behavior standard such as not allowing links to jump
e.stopPropagation() prevent bubbling criteria
Using return false can also prevent the default behavior The code after return is not executed, it is only limited to the traditional registration method, and there is no compatibility problem

The difference between e.target and this

e.target returns the object (element) that triggers the event. this returns the object (element) that binds the event

<div>123</div>
<ul>
    <li>abc</li>
    <li>abc</li>
    <li>abc</li>
</ul>
<script>
// 常见事件对象的属性和方法
// 1. e.target 返回的是触发事件的对象(元素)  this 返回的是绑定事件的对象(元素)
// 区别:e.target 点击了那个元素,就返回那个元素 this 那个元素绑定了这个点击事件,那么就返回谁
var div = document.querySelector('div');
div.addEventListener('click', function(e) {
    console.log(e.target);   //div
    console.log(this);  	 //div
    })
var ul = document.querySelector('ul');
ul.addEventListener('click', function(e) {
    // 我们给ul 绑定了事件  那么this 就指向ul  
    console.log(this);  //ul
    console.log(e.currentTarget);  //ul
    // e.target 指向我们点击的那个对象 谁触发了这个事件 我们点击的是li e.target 指向的就是li
    console.log(e.target);  //li
})
</script>

6.6. Event delegation

Principle: The event listener is set on its parent node, and then uses the bubbling principle to affect the setting of each child node

Function: We only manipulate the DOM once, which improves the performance of the program

6.5 In the case: when registering a click event for ul, and then clicking the li inside, the current li can be obtained by using event.target, and clicking li, the event will bubble up to ul, and if ul has a registered event, event monitoring will be triggered device.

6.7, event type

mouse event focus event keyboard events text event
mouse trigger form gets cursor keyboard trigger form input trigger

6.7.1 Mouse events and their objects

mouse event illustrate
onclick Triggered by left mouse click
onmouseover / onmouseout mouseover/leave trigger
onmouseenter/onmouseleave (no bubbling/recommended) Mouseover/leave trigger (no bubbling/recommended)
onmousemove Triggered by mouse movement
onmouseup / onmousedown Mouse up/down trigger
The difference between mouseover and mouseenter : When triggered on a certain node, as long as the mouse is still in the node, the mouseover event will be triggered multiple times, while the mouseenter event will only be triggered once

Applications:

Disable mouse selection      

document.addEventListener('contextmenu',function(e{e.preventDefault();})

禁止鼠标右键

document.addEventListener('selectstart', function(e){e.preventDefault();})

6.7.2 键盘事件及其对象

键盘事件 触发条件
onkeyup 某个键盘按键被松开时触发,最常用,识别所有的键(包括功能键),不区分字母大小写
onkeydown 某个键盘按键被按下时触发,识别所有的键(包括功能键),不区分字母大小写
onkeypress 某个键盘按键被按下时触发,但是它不识别功能键,比如 ctrl shift 箭头 退格 等,区分字母大小写

三个事件的执行顺序是:keydown–keypress–keyup

键盘对象属性keyCode:返回该键值的ASCII值,我们可以利用keycode返回的ASCII码值来判断用户按下了那个键

七、DOM小结

关于DOM,主要针对的是页面的元素操作,主要有创建,增,删,改,查,属性操作,事件操作

创建

1、document.write   2、innerHTML   3、createElement

1、appendChild   2、insertBefore
1、removeChild
主要修改dom的元素属性,dom元素的内容、属性、表单的值等
修改元素属性:src、href、title 等
修改普通元素内容:innerHTML、innerText
修改表单元素:value、type、disabled
修改元素样式:style、className

Mainly obtain the API methods provided by the DOM for querying elements : getElementById, getElementsByTagName (old usage, not recommended)
New methods provided by H5: querySelector, querySelectorAll (advocated)
use node operations to obtain elements: parent (parentNode), child (children), Brother (previousElementSibling, nextElementSibling) advocates
attribute manipulation Mainly for custom attributes
setAttribute: set the attribute value of dom
getAttribute: get the attribute value of dom
removeAttribute: remove the attribute
event action Event registration, event stream, event object

Next: BOM of JavaScript Advanced Web APl Notes

Guess you like

Origin blog.csdn.net/qq_41045128/article/details/125326181