Day13 - DOM operation of JavaScript, several widths and heights of the page, return to the top and bottom, and operation knowledge related to labels

Posted by MidOhioIT on Tue, 28 Dec 2021 03:19:58 +0100

1, DOM Foundation

DOM: document object model, which is used to manipulate page labels and css
DOM is actually part of BOM

Basic operations of DOM:

 console.log(document) ;    //Print entire page
 console.log(document.documentElement) ;    //Print html
 console.log(document.body) ; //Print body content
 console.log(document.head) ;  //Print head content
 console.log(document.title);  // Print title content 

Note: the content in the title can be edited directly or through document Title Modification. The title is readable and writable

document.title = 'use Baidu Search'    //At this time, the content of the title is modified to < title > Baidu < / Title >

2, Several widths and heights of the page

The width and height of the page includes the actual width and height of the browser, the visual width and height of the browser and the width and height of the page rolled up. Let's take a brief look through specific examples.

        //css Style
        .a{
            width: 2000px;
            height: 3000px;
            background-color: pink;
        }
    <!-- html -->
    <div class="a"></div> 
1. Visual width and height of browser: clientWidth / clientHeight
        //js
        console.log(document.documentElement.clientWidth);    //690
        console.log(document.documentElement.clientHeight);    //705
2. Actual width and height of browser: scrollWidth / scrollHeight

Because most browsers set the margin value of 8px for the body. So the actual width and height of the browser is larger than what we set.

        console.log(document.documentElement.scrollHeight); //3016
        console.log(document.documentElement.scrollWidth); //2008
3. Width and height of the page to be rolled: scrollTop / scrollLeft

The simple understanding is: when the height and width of the visual form is not enough to display the whole page, a scroll bar will appear automatically. When the scroll bar scrolls, the hidden height or width on the page is scrollTop and scrollLeft

scrollTop: the distance from the scroll bar to the top
scrollLeft: the distance from the scroll bar to the left

        console.log(document.documentElement.scrollTop); //2311.199951171875
        console.log(document.documentElement.scrollLeft); //488.79998779296875

3, Back to top

Use ByClassName to get elements: the result must be an array, even if there is only one value

    <!-- html style -->
    <div class="a"></div>
        // js style
        var oDivs = document.getElementsByClassName('a') ;
        console.log(oDivs) ;   //[div.a]
        console.log(oDivs[0]) ;   //<div class="a"></div>
1. Get the element by ByClassName and return to the top
  • document. The documentelement returns the html root node
  • document.documentElement.scrollTop get scroll bar position
<!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>Document</title>
    <style>
        body{
            height: 3000px;
        }
        .a{
            width: 130px;
            height: 130px;
            background-color: pink;
            position: fixed;
            right: 0;
            bottom: 0;
        }
    </style>
</head>
<body>
    <div class="a"></div>

    <script>
        //Get element
        //ByClassName must be an array, even if there is only one value
        var oDivs = document.getElementsByClassName('a') ;
        console.log(oDivs) ;   //[div.a]
        console.log(oDivs[0]) ;   //<div class="a"></div>


        //Perform the return to top operation
        oDivs[0].onclick = function () {
            //Define a timer
            var t = setInterval(function () {
                //The scroll bar position moves upward by 20 every 10 milliseconds
                document.documentElement.scrollTop -= 20 ;
                // The position of the scroll bar is not necessarily divisible by 20
                if(document.documentElement.scrollTop <= 0){
                    //Clear timer
                    clearInterval(t) ;
                }
            },10)
        }
    </script>
</body>
</html>

But at this point, we will find that there is a bug. When we keep clicking to slide up, the slider will accelerate. At this time, we can use function anti chattering and throttling to solve it.

        // js anti shake execution returns the top opcode
        var t ;
        oDivs[0].onclick = function (){
            clearInterval(t) ;
            t = setInterval(function () {
                document.documentElement.scrollTop -= 20 ;
                if(document.documentElement.scrollTop <= 0){
                    clearInterval(t) ;
                }
            },10)
        }
        // js uses throttling to solve the problem of returning the top opcode
        var flag = true ;
        oDivs[0].onclick = function (){
            if(flag){
                flag = false ;
                var t = setInterval(function () {
                    document.documentElement.scrollTop -= 20 ;
                    if(document.documentElement.scrollTop <= 0){
                        clearInterval(t) ;
                        flag = true ;
                    }
                },300)
            }
        }
2. Judge whether it reaches the bottom
<!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>Document</title>
    <style>
        body {
            height: 3000px;
        }

        p {
            position: fixed;
            bottom: 0;
            width: 100%;
            text-align: center;
            display: none;
        }
    </style>
</head>

<body>

    <p id="p">Stop it. It's over</p>

    <script>
        var oP = document.getElementById('p');

        // If this calculation is written in the event, it will be calculated continuously every time it is triggered, so writing it outside can reduce the calculation time - optimize the performance
        // Maximum scroll height = actual height of page - visual height of browser  
        var maxHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight - 10;
        // Judge to reach the bottom

        var t;
        window.onscroll = function () {
            clearTimeout(t);
            t = setTimeout(function () {
                if (document.documentElement.scrollTop >= maxHeight) {
                    console.log('reach the bottom')
                    oP.style.display = 'block' 
                }
            },300)
        }
    </script>
</body>
</html>
3. Method of obtaining elements
  • document.getElementById: get an element
  • document.getElementsByClassName: class is the keyword, and className gets a collection of elements
  • document.getElementsByName: get the element collection through the name attribute (generally only forms have the name attribute)
  • document.getElementsByTagName(): get element collection by tag name

New methods in ES6
querySelectorAll() gets the collection of all elements
querySelector() gets the first

    <input type="text" name="a">
    <input type="text" name="a">
    <input type="text">

    <div class="a"></div>
    <div class="a"></div>

    <script>

        var oInps = document.getElementsByName('a') ;
        console.log(oInps) ;   // [input, input]

        var oInps = document.querySelectorAll('input') ;
        console.log(oInps) ;   // [input, input, input]

        var oDivs = document.querySelectorAll('.a') ;
        console.log(oDivs) ;  // [div.a, div.a]

        var oDivs = document.querySelectorAll('input[name="a"]') ;
        console.log(oDivs) ;  // [input, input]

        var oInp = document.querySelector('input:nth-child(2)') ;
        console.log(oInp) ;  //<input type="text" name="a">
        
    </script>

3, Label content operation

  • value: the content of the input box
  • innerHTML: the content of the tag, identifying the tag
  • innerText: the content of the tag. The tag is not recognized - the tag is regarded as a part of the content
<body>
    <div class="a"></div>
    <input type="text" id="inp">
    
    <script>        
        var oDiv = document.querySelector('.a') ;
        var oInp = document.getElementById('inp') ;
        var content = '<span>ha-ha<span>' ;
        
        // Contents of value input box
        oInp.value = content ;
        
        //Content identification tag of innerHTML tag
        oDiv.innerHTML = content ;   //ha-ha
        
        //The content of innerText tag does not recognize the tag - the tag is regarded as part of the content
         oDiv.innerText = content ;  //<span>Ha ha < span >
    </script>
</body>

4, Gets the properties of the tag

  • Get all attributes: attributes
    Attribute attribute: includes self owned attributes and user-defined attributes
<body>
    <di id="a" class="b" aa="a" vv="s"></div>

    <script>
        //Take object
        var oDiv = document.querySelector('#a') ;
        
        // Attribute attribute: includes self owned attributes and user-defined attributes
        console.log(oDiv.attributes) ;   
        //{0: id, 1: class, 2: aa, 3: vv, id: id, class: class, aa: aa, vv: vv, length: 4}
        //Get the property of id
        console.log(oDiv.attributes.id) ;  //id='a'
        //Get properties of class
        console.log(oDiv.attributes.class) ; // class='b' 
        //Get the properties of aa
        console.log(oDiv.attributes.aa) ;  // aa='a'
    </script>
</body>
  • getAttribute(): method to get specific attribute points
<body>
    
    <di id="a" class="b" aa="a" vv="s"></div>

    <script>
        //Take object
        var oDiv = document.querySelector('#a') ;
        //Gets the property value of the id
        console.log(oDiv.getAttribute('id')) ;  //a
        //Gets the property value of class
        console.log(oDiv.getAttribute('class')) ;  //b
        //Gets the property value of aa
        console.log(oDiv.getAttribute('aa')) ;  //a
    </script>
</body>
  • setAttribute('attribute name ',' attribute value '): add an attribute. If it already exists, it will be overwritten.
<body>
    
    <di id="a" class="b" aa="a" vv="s"></div>

    <script>
        //Take object
        var oDiv = document.querySelector('#a') 

        //Add attribute
        oDiv.setAttribute('class' , 'a') ;
        console.log(oDiv) ;   //At this point, an override is generated, and the attribute value of class becomes' a '

    </script>
</body>
  • Deletes the specified attribute removeAttribute('attribute name ')
<body>
    <di id="a" class="b" aa="a" vv="s"></div>
    <script>

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

        // Delete attribute
        oDiv.removeAttribute(oDiv.id) ;
    </script>
</body>

Note: self owned attributes can be used directly, such as id, and user-defined attributes cannot be used directly

5, Properties of special labels

The self owned attributes on the form can also be abbreviated directly

      <!-- This indicates that the input box is disabled -->
      < input type="text" class="inp1" disabled>    

disabled = true / false
checked = true / false
selected = true / false

<body> 
    <!--  The self owned attributes on the form can also be abbreviated directly -->
    <input type="text" class="inp1" disabled>
    <input type="checkbox" class="inp2" checked>
    <select name="" id="a">
        <option value="+" selected>+</option>
        <option value="-">-</option>
    </select>

    <script>
        //Take object
        var oInp1 = document.querySelector('.inp1') ;
        var oInp2 = document.querySelector('.inp2') ;
        var oInp3 = document.querySelector('#a') ;
        var oOptions = document.querySelectorAll('option') ;

        //Set the timer, and the properties of the input box will change after 1s
        setTimeout(function () {
            // After 1s, the of inp1 changes from disabled to not disabled
            oInp1.disabled = false ;
            // After 1s, inp2 changes from checked to unchecked
            oInp2.checked = false ;
            // After 1s, the symbol of option has + and becomes-
            oOptions[1].selected = true ;
        },1000)
    </script>
</body>


According to these properties, we can make inverse selection and select all. Refer to another blog for details~

6, Label

1. Class name of label
  • className: the return value is a string type, which is compatible with all browsers
    <div class="ano b">66</div>
    
    <script>
        //Take object
        var oDiv = document.querySelector('.b') ;
        console.log(oDiv.className);  // ano b
    </script>
  • classList: is a pseudo array. The attribute is read-only. You cannot modify the class name of an element by direct assignment, but you can add() adds the class name remove() deletes the class name and replace() replaces the class name to modify the classList.
    Method 1:
<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>Document</title>
    <style>
        .on {
            color: pink;
        }
    </style>
</head>

<body>

    <div class="ano b">66</div>

    <script>
        //Take object
        var oDiv = document.querySelector('.b');

        oDiv.onclick = function () {
            //Cut the string into arrays ['ano ',' B '] according to spaces
            var arr = oDiv.className.split(' ');
            //Judge whether this class name exists in the array. If it exists, delete it
            if(arr.includes('on')){
                //Store values that do not contain on in a new array
                var arr2 = [] ;
                for(var i in arr){
                    if(arr[i] !== 'on'){
                        arr2.push(arr[i])
                    }
                }
                //Convert the array into a string, here's this Classname refers to the class attribute of arr
                this.className = arr2.join(' ') ;
            }
            else{
                this.className += ' on' ;
            }
        }
    </script>
</body>

Method 2: use the classList attribute to delete if it exists and add if it does not exist.

        /* css style */
        .on {
            color: pink;
        }
<body>
    <div class="ano b">66</div>

    <script>
        //Take object
        var oDiv = document.querySelector('.b');

        oDiv.onclick = function () {
            if(this.className.includes(' on')){
                this.classList.remove('on')
            }
            else{
                this.classList.add('on')
            }
        }
    </script>
</body>
2. Label style operation
  • Get the style getComputedStyle(obj) ['color ']. If it is an inline style, you can directly get obj style. color
        /* css */
        .a{
            width: 300px;
            height: 300px;
            border: 1px solid #000;
        }
<body>
    <!-- This is an inline style -->
    <div class="a" style="width:500px; color: pink;">555</div>

    <script>
        //Take object
        var oDiv = document.querySelector('.a') ;

         //1 get style
         var style = getComputedStyle(oDiv)['color'] ;
         console.log(style) ;     //rgb(255, 192, 203)

         //If it is an inline style, you can get it directly
         console.log(oDiv.style.color) ;  //pink

    </script>
</body>
  • Set style
    When setting styles, the styles dynamically added by js will appear in the form of inline styles. It should be noted that when obtaining a similar font size attribute, in order to avoid confusing javascript, the reserved characters - need to be converted to hump naming method and changed to fontSize; At the same time, js can only get in-line styles, and non in-line styles cannot be obtained.
<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>Document</title>
    <style>
        /* css */
        .a{
            width: 300px;
            height: 300px;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <!-- This is an inline style -->
    <div class="a" style="width:500px; color: pink;">555</div>

    <script>
        //Take object
        var oDiv = document.querySelector('.a') ;

        // Set style: js dynamically added styles will appear in the form of inline styles
        oDiv.style.color = 'red' ;
        //Change to hump
        oDiv.style.fontSize = '20px' ;
        //js can only get inline styles
        console.log(oDiv.style.color) ;   // red
        console.log(oDiv.style.height) ; //height is a non inline style, so it cannot be obtained

    </script>
</body>

cssText adds multiple styles to the label, but overwrites the previous inline style

       oDiv.style.cssText += 'width:100px;height:100px;color:blue;'
  • The getComputedStyle() method is used to get the CSS style of the specified element. The obtained style is the style of the final rendering effect of the element in the browser.
<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>Document</title>
    <style>
        /* css */
        .a{
            width: 300px;
            height: 300px;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <!-- This is an inline style -->
    <div class="a" style="width:500px; color: pink;">555</div>
    
    <script>
        //Take object
        var oDiv = document.querySelector('.a') ;

        console.log(getComputedStyle(oDiv).height) ;  //300px
        console.log(getComputedStyle(oDiv)['height']) ;  //300px
        console.log(getComputedStyle(oDiv).color) ;  //rgb(255, 192, 203)
    </script>
</body>

currentStyle can only be recognized in IE8 and below. It is feasible in ie and opera, and can not be applied to all browsers. currentStyle gets the calculated style, which is also called current style and final style. Advantages: you can get the final style of the element, including the default value of the browser, instead of style, which can only get the inter line style, so it is more commonly used. Note: you cannot obtain the value of the background attribute of a composite style, but only a single style, such as background color.

      console.log(oDiv.currentStyle.color);

Browser style compatibility. If the browser is IE8 and below, use currentStyle() to obtain the CSS style of the element.

        function css(obj , prop) {
            if(getComputedStyle) {
                return getComputedStyle(obj)[prop]
            } 
            //When the browser is below IE8
            return obj.currentStyle[prop]
        }

        console.log(css(oDiv , 'color'));
        //console.log(css(obj , prop));
2. Add style to label
  1. Add via cssText
    <h1>Label style</h1>
    
    <script>
        //Take object
        var oH1 = document.querySelector('h1') ;

        //Add via cssText
        oH1.style.cssText = 'color:red;width:100px;height:200px;background-color:blue';
        
    </script>
  1. Add class name directly (more convenient)
        /* css style */
        .a {
            color: pink;
            width: 100px;
            height: 100px;
            border-color: yellow;
        }
    <h1>Label style</h1>

    <script>
        //Take object
        var oH1 = document.querySelector('h1') ;
        
        //Add class name directly 
        oH1.classList.add('a') ;
    </script>

Topics: Javascript Front-end css