[javascript] Summary of the operation method of native js on Dom node (1)

CSDN Topic Challenge Phase 2
Participation Topic: Study Notes

*The road to learning is long and long. The process of writing study notes is the process of telling yourself the knowledge. In this process, we record the thinking process, so that we can review and sort out our own thinking in the future. The joy of learning is worse than being alone, and sharing knowledge with more people, why not do it?

1. DOM provides us with the calculated style

var oDiv=document.getElementById('id')

  • window.getComputedStyle(), this method receives an element to be styled and returns a style object.
  • window.getComputedStyle(oDiv);//style object
  • window.getComputedStyle(oDiv).getPropertyValue("width")//Get the width
  • Shorthand: window.getComputedStyle(oDiv)['width']

getComputedStyle.getPropertyValue() is not compatible with IE6, 7, and 8, so it needs to be used separately

  • it must use camelCase
  • oDiv.currentStyle.paddingLeft;
  • oDiv.currentStyle[“paddingLeft”];

Summarize:

function getAllComputedStyle(obj,property){
    
          
  if(window.getComputedStyle){
    
    
    //现在要把用户输入的property中检测一下是不是驼峰,转为连字符写法
    //强制把用户输入的词儿里面的大写字母,变为小写字母加-
    //paddingLeft  →  padding-left
    property = property.replace(/([A-Z])/g , function(match,$1){
    
    
      return "-" + $1.toLowerCase();
    });
    return window.getComputedStyle(obj)[property];
  }else{
    
    
    //IE只认识驼峰,我们要防止用户输入短横,要把短横改为大写字母
    //padding-left  → paddingLeft 
    property = property.replace(/\-([a-z])/g , function(match,$1){
    
    
      return $1.toUpperCase();
    });
    return obj.currentStyle[property];
  }
}
var oDiv = document.getElementsById("id");
console.log(getAllComputedStyle(oDiv,"padding-left"));

2. Shortcut location and size

DOM has provided us with the calculated style, but it is still inconvenient, so DOM provides us with some APIs:

ele.offsetLeft (the distance to the left of the nearest positioned element)

ele.offsetTop (the distance from the top of the nearest positioned element)

ele.offsetWidth (own width)

ele.offsetHeight (own width)

ele.clientWidth (own width+padding)

ele.clientHeight (own height+padding)


3.getBoundingClientRect gets the position relative to the upper left corner of the viewport

  • document.getElementById(‘id’).getBoundingClientRect();

    // — positions relative to the upper left corner of the viewport, both in numer —

    // top: 100 — the distance between the top border of the box and the top of the viewport

    // bottom: 302 — the distance between the bottom border of the box and the top of the viewport = top + height

    // left: 394 — the distance from the left border of the box to the left of the viewport

    // right: 796 — the distance from the right border of the box to the left side of the viewport = left + width

    // x: 394 — the distance from the top left corner of the box relative to the left side of the viewport

    // y: 100 — the distance from the top left corner of the box relative to the top of the viewport

    // width and height of the box

    // width: 402

    // height: 202


4. Monitor scrolling, the browser obtains the height of the scroll bar, and bottoms out

·Rolling distance

  • IE6/7/8 document.documentElement.scrollTop
  • IE9 and above window.pageYOffset or document.documentElement.scrollTop
  • Safari window.pageYOffset or document.body.scrollTop
  • Firefox window.pageYOffset or document.documentElement.scrollTop
  • Chrome document.documentElement.scrollTop

·Scroll bar height

  • Scroll bar height document.body.scrollHeight and document.documentElement.scrollHeight
  • Scroll bar width document.body.scrollWidth and document.documentElement.scrollWidth

· Monitor scrolling, bottoming out, scrolling to the bottom

// 是否滚动到底部
function handleScroll(e){
    
    
  let Dom=e.currentTarget
  if(Dom === Dom.window || Dom === 'window')Dom=document.documentElement || document.body
  let scrollTop = Dom.scrollTop // 滚动条距离顶部的距离
  let windowHeight = Dom.clientHeight // 可视区的高度
  let scrollHeight = Dom.scrollHeight //dom元素的高度,包含溢出不可见的内容
  if ( scrollTop + windowHeight >=scrollHeight) {
    
    
    console.log('到底了')
  }
}
// 滚动到顶部,或者具体位置
function scrollToTop(el, value = 0, time = 200) {
    
    
    let Dom = el
    if (Dom === Dom.window || Dom === 'window')Dom = document.documentElement || document.body
    const beginValue = Dom.scrollTop
    if (beginValue <= 0) {
    
    
      return false
    }
    let toValue = value
    if (value == 'last') {
    
    
      toValue = Dom.scrollHeight
    }
    const chaTop = (beginValue - toValue)
    const chaTime = time / 30
    const progressTop = chaTop / chaTime
    let changeTop = 0
    const rAF = window.requestAnimationFrame || (func => setTimeout(func, chaTime))
    const frameFunc = () => {
    
    
      changeTop = changeTop + progressTop
      if ((beginValue - changeTop) < toValue && beginValue - toValue > 0) {
    
    
        Dom.scrollTop = toValue
        return
      }
      if ((beginValue - changeTop) > toValue && beginValue - toValue < 0) {
    
    
        Dom.scrollTop = toValue
        return
      }
      if (changeTop > toValue && value == 'last') {
    
    
        Dom.scrollTop = toValue
        return
      }
      Dom.scrollTop = beginValue - changeTop
      rAF(frameFunc)
    }
    rAF(frameFunc)
  }
window.onscroll =handleScroll
scrollToTop(window,0)
// 或者
document.getElementById('id').addEventListener('scroll',handleScroll,false)

Detailed explanation of the difference between e.target and e.currentTarget

  • target: the source component that triggered the event (the component where the event is registered/bound)

  • currentTarget: the current event triggered by the event

  • (The current event may be the source component that triggered the event, or the triggered event component (that is, the child element that triggered the event source component). At this time,
    clicking on the child element or the parent element is the current event, and e.currentTarget is applied).

5. Get the attributes on the Dom node (getAttribute, setAttribute)

  • Get
    Dom.getAttribute(name)
  • Set
    Dom.setAttribute(name,value)

illustrate:

  • name: the attribute name to be set
  • value: the attribute value to be set

6.DOM node create node, add node, delete node, copy node, replace node

·Create node

  • createElement() method: create element nodes
var element = document.createElement("p");  //创建段落元素节点
// var element = document.createTextNode('xxx') //创建文本节点
element.className = "red";
document.body.appendChild(element);

·Add node

  • node.appendChild(child)
//创建元素节点
var li =document.createElement('li');
//添加节点
var ul = document.querySelector('ul');
ul.appendChild(li);
  • node.insertBefore(child, specified element)//insert before the specified element
var liDom = document.createElement('li');
ul.insertBefore(liDom,ul.children[0]);

·Delete node

  • node.removeChild(child);
var ul = document.querySelector('ul');
ul.removeChild(ul.children[0]);

or

const child = document.getElementById("p1");
child.parentNode.removeChild(child);

· Duplicate node

  • node.cloneNode();
  • The node.cloneNode() method returns a copy of the node on which the method was called. Also known as clone node or copy node. Empty or false in the brackets means a shallow copy, only the node is copied but the content is not copied. True in the brackets means deep copy, copy node, copy content
var ul = document.querySelector('ul');
var liDom = ul.children[0].cloneNode(true);
ul.appendChild(liDom);

·Replace Node

  • node.replaceChild(child, element to be replaced);
<div id="div1">
  <p id="p1">这是一个段落。</p>
  <p id="p2">这是另一个段落。</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("这是新文本。");
para.appendChild(node);

var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para, child);
// child.parentNode.replaceChild(para, child);
</script>

·Judging whether the Dom node is loaded

document.addEventListener("DOMContentLoaded",function(){
    
    
    
})

7. Determine the node type

var DOM=document.getElementById(“id”)

  • DOM[0].nodeName: label name
  • DOM[0].nodeType: node type
  • DOM[0].nodeValue: node value

//element node nodeName tag name nodeType 1 nodeValue null

//Attribute node nodeName attribute name nodeType 2 nodeValue attribute value

//Text node nodeName #text nodeType 3 nodeValue The value of the text

8. Get elements

Use the methods provided by DOM to get elements

  • document.getElementById('id') // id acquisition
  • document.getElementsByClassName('class')// class name acquisition
  • document.getElementsByTagName('div') // Get the tag name
  • document.getElementsByName(‘name属性’) // <button name="aaa">我是button</button>
  • document.querSelector(‘.class’) 或者 document.querSelector(‘#id’)
  • document.querySelectorAll('.class') // Get all classes

Use the node hierarchy to get elements

  • Use parent-child sibling node relationship to get elements

9. Node relationship and acquisition method

  • node.parentNode // Get the parent node (return the nearest parent node)
  • parentNode.childNodes(index) // Get child nodes (return child nodes, including element nodes, text nodes, etc.)
  • parentNodes.children(index) // parentNodes.children is a read-only property that returns all child element nodes, it only returns child element nodes, and other nodes do not return
  • parentNode.firstChild // returns the first child node, returns null if not found, and also includes all nodes
  • parentNode.lastChild // return the last child node, return null if not found, and also include all nodes
  • parentNode.firstElementChild // Return the first child element node, if not found, return null (only supported by IE9 and above)
  • parentNode.lastElementChild // Returns the last child element node, if not found, returns null (only supported by IE9 and above)
  • node.nextSibling // returns the next sibling node of the current element, if not found, returns null, similarly, includes all nodes
  • node.previousSibling // Returns the previous sibling node of the current element, and returns null if it cannot be found. Similarly, it also includes all nodes
  • node.nextElementSibling // Returns the next sibling element node of the current element, and returns null if it cannot be found (only supported by IE9 and above)
  • node.previousElementSibling // returns null if the previous sibling node of the current element cannot be found (supported only on IE9 and above)

10. The difference between innerHTML, innerText and outerhtml

 <div id="test"> 
   <span style="color:red">test1</span> test2 
</div>

innerHTML:
The content written in innerHTML can be parsed into tags, and the tags in the node are also obtained

  1. Get:
    the value of innerHTML is " <span style="color:red">test1</span> test2 "
    insert image description here
  2. write:
    insert image description here

innerText:
The content written by innerText can only be displayed in the browser as text, and the displayed text is obtained

  1. Obtain:
    insert image description here
  2. write:
    insert image description here

outerhtml:
Outerhtml's current self and internal tags

  1. Get:
    the value of outerHTML is " <div id="test"><span style="color:red">test1</span> test2</div>"
    insert image description here
  2. write:
    insert image description here

OTHER

1. DOM provides us with the calculated style
2. Shortcut position and size
3. getBoundingClientRect obtains the position relative to the upper left corner of the viewport
4. Monitor scrolling, the browser obtains the height of the scroll bar, and touches the bottom

7. Determine the node type
8. Get elements

Guess you like

Origin blog.csdn.net/qq_40591925/article/details/127083744