JS——DOM

get element

  1. getElementById(id) Find elements by element id

Parameters: id is a case-sensitive string representing the unique value of the element to be found.

Returns an element object

  1. getElementsByTagName(name) Find elements by tag name

The returned collection of obtained element objects is stored in the form of a pseudo-array

getElementsByClassName(name) Find elements by class name
querySelector (form of CSS selector) Finds the first HTML element that matches the specified CSS selector (id, classname, type, attribute, attribute value, etc.)
querySelectorAll (CSS selector form) All elements of the specified selector

Get the body / html element

document.body  //返回 body 元素对象
document.documentElement  //返回 html 元素对象

operating elements

element.innerHTML It can be used to obtain or replace the content of HTML elements, identify HTML tags, and keep them all when reading and writing
element.innerText HTML tags are not recognized
element.attribute get attribute value
element.getAttribute('attribute') Get custom attribute value
element.attribute = ‘值’ Change or set the value of an attribute of an HTML element; attributes are named in camel case
element.setAttribute = ('attribute', 'value') Change or set custom attributes (usually start with data-)
element.removeAttribute('attribute') remove an attribute
element.dataset.index H5's new acquisition of custom attributes; dataset is a collection of all custom attributes starting with data, only available in ie11
element.style.property = new style Change the style of HTML elements, add inline styles, and have higher weight

Modify styles using class names

//当样式较多,或者功能复杂时,可以直接在CSS内创建一个类名写入样式,在js内添加这个类,以类名为"change"为例
element.className = 'change';
//className 会直接更改元素的类名,覆盖原先的类名,如果想要保留之前的样式,可以写成'change 原先的类名'即在多个类名间添加空格

Hide, show: 1. visibility = hidden 2. visibility = visible

node operation

node node

Element node (nodeType=1), attribute node (2), text node (3), comment node

parentNode
//父级节点,返回离元素最近的节点
//子节点 
//1. childNodes 所有的子节点 包含元素节点 文本节点等等
//2. 
children 获取所有的子元素节点
//第一个子节点,最后一个子节点
//1. firstChild lastChild 包含元素节点 文本节点等等
//2. firstElementChild (id9以上支持)lastElementChild (ie9以上支持) 只有元素节点
//实际开发写法  
element.childern[0]...element.childern[element.childern.length - 1]
//兄弟(sibling)节点
//1. nextSibling previouSibling
//2. nextElementSibling previousElementSibking
//以上黑色为常用的

create, delete, add elements

  1. document.createElement(‘tagName’)
  2. node.removeChild(child) deletes the child node in the parent node
  3. node.appendChild(child)

Adds a node to the end of the specified parent's children

  1. node.insertBefore(child, specified element)

Adds a node to the front of the child nodes of the specified parent node

  1. document.replaceChild(element) replaces the element
  2. document.write(text) The document is executed, causing all pages to be redrawn
  3. node.clone(); clone node

If the parentheses are empty or false inside, only the copy node itself will be cloned, and the child nodes inside will not be cloned; if the parentheses parameter is true, deep copy will copy the node itself and all child nodes inside

The difference between innerHTML and createElement

innerHTML is more efficient in creating multiple elements (do not concatenate strings, but concatenate them in the form of arrays), and the structure is slightly more complicated

createElement() is slightly less efficient to create multiple elements, but the structure is clearer

eg:class=inner的元素内 添加100个空链接
var inner = document.querySelector('.inner');
var array = [];
for(var i = 0; i < 100; i++) {
    
    
    array.push('<a href="#"></a>');
}
inner.innerHTML = array.join('');//将数组转为字符串

Prevent link jump

<a href="javascript:;">xxx</a>

form

<form action="url地址"> //规定当提交表单时,向何处发送表单数据
用户名: <input type="text" value="输入内容" name="">
<button></button>
</form>

var btn = document.querySelector('button');
var input = document.querySelector('input');
btn.onclick = function() {
    
    
    this.disabled = true //禁用按钮
}

show hidden password

var flag = 0;
eye.onclick = function() {
    
    
    if(flag == 0) {
    
    
        pwd.type = 'text';
        flag = 1;
    } else {
    
    
        pwd.type = 'password';
        flag = 0;
    }
}

sprite cycle

for(var i = 0; i < lis.length; i++) {
    
    
    //索引号×一个数
    var index = i * 一个数
    lis[i].style.backgroundPosition = '0 -' + index + 'px';
}

Form select all, deselect all

<table>
    <thead>
    	<tr>
        	<th>
            	<input type="checkbox" id="j_cbAll"/>
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody id="j_tb">
    	<tr>
        	<th>
            	<input type="checkbox" />
            </th>
            <th></th>
        </tr>
        <tr>
        	<th>
            	<input type="checkbox" />
            </th>
            <th></th>
        </tr> 
    </tbody>
</table>
var j_cbAll = document.getElementById('j_cbAll') //全选按钮
var j_tbs = document.getElementById('j_tb').getElementsByTagName('input');  //tbody里面的所有复选框
j_cbAll.onclick = function() {
    
    
    //this.checked 返回当前复选框的选中状态,true为选中,false为未选中
    for(var i = 0; i < j_tbs.length; i++) {
    
    
        j_tbs[i].checked = this.checked
    }
}
for(var i = 0; i < j_tbs.length; i++) {
    
    
    j_tbs[i].onclick = function() {
    
    
        //flag 控制全选按钮是否选中
        var flag = true;
        //每次点击复选框 都循环检查所有小按钮是否全被选中
        for(var i = 0; i < j_tbs.length; i++) {
    
    
            if(!j_tbs[i].checked) {
    
    
                flag = false;
                break; //只要一个没选中,就跳出for循环
            }
        }
        j_cbAll.checked = flag;
    }
}

The required attribute prevents the form from being submitted if the form field (fname) is empty

data verification

HTML constraint validation

  1. image button

specific

animation

event listener

event type

onfocus gain focus
onblur lose focus
onmouseover mouse over
onmouseout mouse out

event flow

Event flow refers to the order in which events are received from a page.

DOM event flow refers to the process of propagating in a specific order among element nodes when things happen.

  1. capture phase
  2. current target stage
  3. bubbling stage

Notice::

  1. JS code can only perform one of the capturing or bubbling phases
  2. onclick and attachEvent can only get the bubbling phase
  3. addEventListener(type, function() {}, ), if the third parameter is true, it means that the event handler is called in the event capture phase; if it is false (if not written, the default is false), it means that the event processing is called in the event bubbling phase program.
  4. In actual development, we rarely use event capture and pay more attention to event bubbling
  5. Some events do not bubble, such as onblur, onfocus, onmouseenter, onmouseleave

bind event

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

//传统方法
​    div.onclick = function() {
    
    }
//事件监听 div.addEventListener(type,,)
//(1)
​    div.addEventListener('click',function(){
    
    })
//(2)
​    div.addEventListener('click', fu)function fu() {
    
    }

delete event

//传统方法
div.onclick = null;
//法二
div.addEventListener('click', fn)function fn() {
    
    // 方法体

​      div.removeEventListener('click', fn);}

event object

div.onclick = function(event) {}

div.addEventListener(‘click’, function(event) {})

  1. event is an event object
  2. The event object will only exist if there is an event. It is automatically created by the system for us and does not need to pass parameters
  3. The event object is a combination of a series of related data of our event, which is related to the event (eg: the mouse click event contains the relevant information of the mouse, and the keyboard event contains the relevant information of the keyboard)
  4. Compatibility issues Compatibility writing: event = event || window.event

Common Properties and Methods

e.target

Returns the object (element) that triggered the event

eg:

  <ul>
        <li></li>
        <li></li>
    </ul>
<script>
      var ul = document.querySelector('ul');
	  ul.addEventListener('click', function(e) {
          console.log(e.target); //返回<li></li>
          console.log(this);   //返回<ul></ul>
          //this 返回绑定该事件的元素
      })
</script>

e.type returns the event type

e.preventDefault()

prevent default behavior (event)

var a = document.querySelector('a');
a.addEventListener('click', function(e) {
    e.preventDefault();// dom 标准写法
});
// 传统注册方式-----------------------------------
a.onclick = function(e) {
    e.preventDefault(); //普通浏览器
    e.returnValue;  //低版本浏览器 ie678
    return false; //没有兼容性问题,但是 return 后面的代码就不执行了
}

e.stopPropgation()

prevent bubbling events

var a = document.querySelector('a');
a.addEventListener('click', function(e) {
   e.stopPropgation()
});

Event delegation + exclusive thinking

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

<ul>
	<li></li>
    <li></li>
    <li></li>
 	<li></li>
</ul>
var ul = document.querySelector('ul');
var li = ul.querySelector('li');
ul.addEventListener('click', function() {
//排他思想-----------------------------------
    for(var i = 0;i < li.length; i++) {
        li[i].style.backgroundColor = '';
    }
//------------------------------------------
    e.target.style.backgroundColor = 'pink';
})

Common mouse events

contextmenu disable right click menu

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

selectstart prohibits selected text

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

Case: follow mouse events

e.clientX Returns the X coordinate of the mouse relative to the visible area of ​​the browser window
e.clientY Returns the Y coordinate of the mouse relative to the visible area of ​​the browser window
e.pageX Returns the X coordinate of the mouse relative to the document page
e.pageY Returns the Y coordinate of the mouse relative to the document page
e.screenX Returns 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

mousemove

img {
    
    
    position: absolute;
}
var pic = document.querySelector('img');
document.addEventListener('mousemove', function(e) {
    
    
    //获取鼠标在文档中的坐标
    var x = e.pageX;
    var y = e.pageY;
    // 记住加上单位!!!  图片居中还要减去图片的一半
    pic.style.left = x + 'px';
    pic.style.top = y + 'px';
})

Common keyboard events

keyup Triggered when a keyboard key is released
keydown Fired when a keyboard key is pressed
keypress Triggered when a keyboard key is pressed, but does not recognize the function key

Execution sequence of three events: keydown - keypress - keyup

keyup and keydown are not case sensitive

keypress is case sensitive

e.keyCode Returns the ASCII value of the key

Guess you like

Origin blog.csdn.net/m0_63300737/article/details/122755780