JavaScript from getting started to mastering

JavaScript from getting started to mastering

On the charm of JavaScript

What is javscript

  • Principles of web effects
    • JavaScript is modifying styles (documents)
  • Process of writing JS
    • Layout: HTML + CSS
    • Attribute: determines the attribute to modify
    • Event: determine what the user does (product design)
    • Write JS: in the event, use js to modify the style of page elements

First JS effect: mouse prompt box

  • Analysis effect and realization principle

    • Style: div display / none
    • Event: onmouseover / onmouseout
    • Hands on writing effect
  • Special effects Foundation

    • Event driven: onmouseover
    • Element attribute operation: obj style. [...]
    • Summary of the implementation principle of special effects: responsive user operation and modification of page element style
  • Compatibility issues

    // div2.style.display='block'; //  Some browsers are incompatible
    document.getElementById('div2').style.display='block'; // All browsers compatible
    
  • function

    • Make more complex effects
    • Writing code directly inside an event can be messy
      • Introduce the basic form of function()
      • Put the JS tag into the function, similar to the class in css
      • Use of variables: aliases
    • Definition and call
      • Function definition: tells the system that this function exists and will not be executed
      • Function call: execute the code in the function
      • Relationship and difference
  • code

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>first JS effect</title>
    
        <style>
          #div2 {
            display: none; 
            background: red; 
            width: 100px; 
            height: 50px; 
            font-size: 16px;
          }
          #div1 {
            display: block; 
            background: red; 
            width: 100px; 
            height: 100px; 
            font-size: 16px;
          }
        </style>
    
        <script>
    
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
    
        // Show div2
        function show() {
          // div2.style.display='block'; //  Some browsers are incompatible
          get('div2').style.display='block';
        }
    
        // Hide div2
        function hide() {
          // div2.style.display='none'; //  Some browsers are incompatible
          get('div2').style.display='none';
        }
    
        // div1 turns green
        function toGreen() {
         get('div1').style.background='green';
        }
    
        // div1 turns blue
        function toblue() {
          get('div1').style.background='blue';
        }
    
        // div1 turns red
        function toRed() {
          get('div1').style.background='red';
        }
        
        // Click cycle color change
        var i = 0;
        function changeColor() {
          console.log('i=',i)
          if (i == 0) {
            toGreen();
            i++;
            console.log('i=',i)
            return;
          } 
          if (i == 1) {
            toblue();
            i++;
            console.log('i=',i)
            return;
          } 
          if (i == 2) {
            toRed();
            i = i - 2;
            console.log('i=',i)
            return;
          }
        }
        </script>
      </head>
    
      <body>
         <!-- Call the on page function to modify the style -->
        <input type="button" onclick="changeColor()" value="Button">
        <div id="div1">
        </div>
          <!-- Hanlin Academician JS modify style -->
        <input type="checkbox" onmouseover="div2.style.display='block';" onmouseout="div2.style.display='none';" value="Button">  
        <div id="div2">
          <p>written words<br>Text 2</p>
        </div>
      </body>
    </html>
    

Web skinning and if judgment

  • Web skinning

    • Tudou "light on" and "light off effect"
    • Any tag can be added with ID, including link
    • The properties of any tag can be modified
    • How to write in HTML, how to write in JS
  • if judgment

    • Special effect implementation principle
    • if basic form
    • JS = assignment, = = judgment
    • Add JS for a link
      • <a href="javascript:;"></a>
    • Use of className
      • class is a keyword, so use className instead
      • What is written in other HTML is written in JS
  • code

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <link id="link1" rel="stylesheet" type="text/css" href="css/grey.css">
    
        <script>
        function changeColor() {
          if (document.getElementById('b1').value == 'Turn off the lights') {
            document.getElementById('link1').href = 'css/black.css';
            document.getElementById('b1').value = 'turn on the light';
            console.log('black')
          } else {
            document.getElementById('link1').href = 'css/grey.css';
            document.getElementById('b1').value = 'Turn off the lights';
            console.log('bl2:', document.getElementById('link1').href)
          }
        }
    
        function changeText() {
          document.getElementById('text1').value = '456';
          document.getElementById('text1').title = 'Text1';
        }
    
        function showHide() {
          var div2 = document.getElementById('div2');
          if(div2.style.display == 'block') {
            div2.style.display ='none';
            console.log('1');
          } else {
            div2.style.display = 'block';
            div2.style.background = 'blue';
          }
          console.log('display:', div2.style.display);
        }
    
        function class1() {
          var div = document.getElementById('div4');
          div.className='div5';
          div.id='div5';
        }
        </script>
      </head>
      <body>
        <!-- skin peeler -->
        <input id="b1" type="button" onclick="changeColor()" value="Turn off the lights">
        <div id="div1">1</div>
        <div id="div2">2</div>
        <div id="div3">3</div>
        <input type="button" value="Show hide div2" onclick="showHide()">
        <br>
        <!-- HTMl What's in it, JS What's in it -->
        <input id="text1" type="text" value="123">
        <input type="button" value="Change text" onclick="changeText()">
        <br>
        <!-- a Use of links -->
        <a href="javascript:;">javascript:;</a>
    
        <!-- className Use of -->
        <div id="div4">4</div>
        <input type="button" value="className" onclick="class1()">
      </body>
    </html>
    

Function parameter transfer

  • Change background color

    • Function parameters: parameters are placeholders
      • Pass arguments to variables in functions
  • Change any style of div

    • The second way to manipulate attributes
      • When the attribute to be modified is uncertain: element style [variable / String] = variable / String
      • Used in JS All places can be replaced by [];
      • The difference and relationship between string variables: strings with quotation marks and variables without quotation marks
    • Pass the property name as a parameter
  • style and className

    • element.style.attribute = variable/character string
      
      • Style is to modify the inline style
    • In line styles have the highest priority. Modifying className later will not have an effect

    • Suggestion: operate on only one style, either style or className

  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Function parameter transfer</title>
    
        <style>
          div {
            display: block; 
            background: red; 
            width: 100px; 
            height: 100px; 
            font-size: 16px;
          }
    
          .div2 {
            display: block; 
            background: grey; 
            width: 100px; 
            height: 100px; 
          }
        </style>
    
        <script>
    
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
    
        // div1 turns green
        function toGreen() {
         get('div1').style.background='green';
        }
    
        // div1 turns blue
        function toblue() {
          get('div1').style.background='blue';
        }
    
        // div1 turns red
        function toRed() {
          get('div1').style.background='red';
        }
        
        // Click cycle color change
        var i = 0;
        function changeColor() {
          console.log('i=',i)
          if (i == 0) {
            toGreen();
            i++;
            console.log('i=',i)
            return;
          } 
          if (i == 1) {
            toblue();
            i++;
            console.log('i=',i)
            return;
          } 
          if (i == 2) {
            toRed();
            i = i - 2;
            console.log('i=',i)
            return;
          }
        }
    
        // Function parameter transfer
        function toColor(color, width) {
          get('div1').style.background = color;
          get('div1').style.width = width;
        }
        // Pass the property name as a parameter
        function chgName(name, width) {
          // get('div1').style.name = width; // name is assigned as an attribute
          get('div1')['style'][name] = width; // Arrays can be added with strings or variables
        }
        // Style priority
        function chgClass(className) {
          get('div1').className =  className; 
        }
        </script>
      </head>
    
      <body>
        <!-- Call the on page function to modify the style -->
        <input type="button" onclick="changeColor()" value="loop">
        <!-- Function parameter transfer -->
        <input type="button" onclick="toColor('green', '200px')" value="Turn green">
        <input type="button" onclick="toColor('blue', '300px')" value="Turn blue">
        <input type="button" onclick="toColor('red', '400px')" value="Turn red">
        <input type="button" onclick="chgName('height', '200px')" value="Get higher">
        <input type="button" onclick="chgClass('div2')" value="class Graying">
        <div id="div1"></div>
    
      </body>
    </html>
    

Extract inter line events

  • Extract events

    • Add events to elements

      • Like other attributes, events can be added with JS:

        element.event = Function name/function;
        
        • You cannot add parentheses. You can directly execute the function with parentheses
      • window. The meaning of onload: wait for the page to load before executing JS

      • Behavior (js), style (css) and structure (html) are separated

  • Get a set of elements

    • element.getElementsByTagName('Tag name')
      
      • Use of arrays
      • Array properties
    • Implementation of select all

  • Code: same as below

Loop while and for

  • Introducing the concept of loop with while

    • while loop syntax
      • Self increasing significance
      • Loop composition: initialization, condition, statement and self increment
  • for loop

    • Replace the while loop with for
      • Use the for loop to generate events for a set of elements
      • When to use a loop -- a set of elements
    • example
      • Select all -- checked attribute
      • Inverse selection -- for loop matching with if judgment
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Extract inter line events and loops</title>
    
        <style>
          div {
            display: block; 
            border: 1px solid black; 
            width: 100px; 
            height: 100px; 
            margin: 10px;
            float: left;
          }
        </style>
          
        <script>
          window.onload = function () {
            // Encapsulate getElementById function
            function get(id) {
              return document.getElementById(id);
            }
    
            // Encapsulate getElementsByTagName
            function gets(tagName) {
              return document.getElementsByTagName(tagName)
            }
    
            // Extract inter line style
            get('btn1').onclick = function () {
              get('btn1').value = 'Extraction succeeded';
            }
    
            // Modify an element in a group of elements
            get('btn2').onclick = function () {
              gets('div')[2].style.background = 'blue';
            } 
    
            // Modify a set of elements - while loop
            get('btn3').onclick = function () {
              var i = 0;
              while ( i < gets('div').length ) {
                gets('div')[i].style.background = 'yellow';
                i++;
              }
            } 
            // for
            get('btn4').onclick = function () {
              for (var i = 0; i < gets('div').length; i++ ){
                gets('div')[i].style.background = 'pink';
              }
            } 
    
            // The implementation of select all does not require div for if judgment
            get('btn5').onclick = function () {
              for (var i = 0; i < gets('input').length; i++ ){
                if (gets('input')[i].type == 'checkbox'){
                  if (gets('input')[i].checked == false) {
                    gets('input')[i].checked = true;
                  } else {
                    gets('input')[i].checked = false;
                  }
                }
              }
            } 
            // Element getElementsByTagName method single div
            get('btn6').onclick = function () {
              var div2 = get('div2');
              var inp = div2.getElementsByTagName('input');
              for (var i = 0; i < inp.length; i++ ){
                // console.log(inp);
                if (inp[i].checked == false) {
                  inp[i].checked = true;
                } else {
                  inp[i].checked = false;
                }
              }
            }
            // Element getElementsByTagName method multiple div
            get('btn7').onclick = function () {
              var div2 = gets('div');
              for (var i = 0; i < div2.length; i++ ){
                var div = gets('div')[i];
                var inps = div.getElementsByTagName('input');
                for (var a = 0; a < inps.length; a++){
                  if (inps[a].checked == false) {
                    inps[a].checked = true;
                  } else {
                    inps[a].checked = false;
                  }
                }
              }
            }  
          };
        </script>
      </head>
    
      <body>
        <!-- Extract inter line style -->
        <input id="btn1" type="button" value="Button">
        <!-- Modify an element in a group of elements -->
        <input type="button" id="btn2" value="Change the third element">
        <!-- Modify a set of elements-loop -->
        <input type="button" id="btn3" value="while Loop to change a set of elements">
        <input type="button" id="btn4" value="for Loop to change a set of elements">
        <input type="button" id="btn5" value="Select all">
        <input type="button" id="btn6" value="Select all 2">
        <input type="button" id="btn7" value="Select all 3">
        <div><input type="checkbox" name="1" id="c1"></div>
        <div><input type="checkbox" name="1" id="c2"></div>
        <div><input type="checkbox" name="1" id="c3"></div>
        <div><input type="checkbox" name="1" id="c4"></div>
        <div><input type="checkbox" name="1" id="c5"></div>
    
        <div id="div2">
          <input type="checkbox" name="" id="">
          <input type="checkbox" name="" id="">
          <input type="checkbox" name="" id="">
          <input type="checkbox" name="" id="">
          <input type="checkbox" name="" id="">
          <input type="checkbox" name="" id="">
          <input type="checkbox" name="" id="">
        </div>
    
      </body>
    </html>
    

Navigation bar tab

  • Button implementation

    • Add event
      • Use of this: refers to the element of the current event
    • Clear all buttons before selecting the current button
  • Content implementation (ul)

    • Hide all ul before displaying the current ul
      • Use of index value: when to use index value
      • HTML index will be filtered by FireFox
      • JS add index
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Navigation tab</title>
        <style>
          body {
            margin: 0;
            padding: 0;
          }
          #div2 {
            width: 200px;
            height: 200px;
            margin-top: 20px;
            position: relative;
          }
          #div1 {
            width: 200px;
            height: 20px;
            position: absolute;
            top: 0px;
          }
          ul {
            margin: 0;
            padding: 0;
            display: block;
            background: rgb(157, 234, 253);
            float: left;
            position: absolute;
            display: none;
            width: 200px;
            height: 200px;
          }
          .ul {
            display: block;
          }
          a {
            display: block;
            float: left;
            width: 49px;
            height: 20px;
            background: rgb(7, 184, 253);
            border-left: 1px solid rgb(255, 0, 234);
            text-decoration: none;
          }
          .a {
            background: rgb(32, 108, 221);
          }
        </style>
        <script>
          window.onload = function (){
            // Encapsulate getElementById function
            function get(id) {
              return document.getElementById(id);
            }
            // Encapsulate getElementsByTagName
            function gets(tagName) {
              return document.getElementsByTagName(tagName)
            }
            // Show first element
            gets('ul')[0].className = 'ul';
            // When the mouse covers a label, the corresponding element is displayed
            for (var i = 0; i < 4; i++) {
              gets('a')[i].index = i;
              gets('a')[i].onmouseover = function () {
                for (var a = 0; a < 4; a++) {
                  gets('ul')[a].className = '';
                  gets('a')[a].className = '';
                }
                // console.log(this);
                gets('ul')[this.index].className = 'ul';
                this.className = 'a';
              }
            }
          }
        </script>
      </head>
      <body>
        <div id="div1">
          <a href="javascript:;" id="a0">1</a>
          <a href="javascript:;" id="a1">2</a>
          <a href="javascript:;" id="a2">3</a>
          <a href="javascript:;" id="a3">4</a>
        </div>
        <div id="div2">
          <ul>
            <li>1</li>
            <li>1</li>
            <li>1</li>
          </ul>
          <ul>
            <li>2</li>
            <li>2</li>
            <li>2</li>
          </ul>
          <ul>
            <li>3</li>
            <li>3</li>
            <li>3</li>
          </ul>
          <ul>
            <li>4</li>
            <li>4</li>
            <li>4</li>
          </ul>
        </div>
      </body>
    </html>
    

JS simple calendar

  • Program implementation idea

    • Similar to tabs, except there is only one div below
    • Use of innerHTML
  • Use of arrays

    • Definition: arr = [1, 2, 3]
    • Use: arr[0]
  • String splicing

    • Function: splice two strings
    • Question: priority in splicing
      • Add nearby, and add numbers after the string in parentheses
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Simple calendar</title>
        <style>
          body {
            margin: 0;
            padding: 0;
          }
          td {
            border: 5px solid rgb(218, 218, 218);
            width: 59px;
            height: 59px;
            text-align: center;
            background: rgb(83, 83, 83);
            color: white;
          }
          .td {
            background: rgb(255, 255, 255);
            color: rgb(0, 0, 0);
          }
    
          /* Calendar number area */
          #t1 {
            border: 10px solid rgb(218, 218, 218);
            margin:0 auto;
            position: relative;
            width: 240px;
            height: 320px;
            background: rgb(218, 218, 218);
          }
    
          /* Text below */
          #d2 {
            margin:0 auto;
            width: 240px;
            height: 100px;
            background: rgb(218, 218, 218);
          }
          #p1 {
            position: relative;
            margin: auto;
            width: 205px;
            height: 80px;
            background: rgb(255, 255, 255);
          }
        </style>
        <script>
          window.onload = function () {
            // Encapsulate getElementById function
            function get(id) {
              return document.getElementById(id);
            }
            // Encapsulate getElementsByTagName
            function gets(tagName) {
              return document.getElementsByTagName(tagName)
            }
            // Get all td, register onmouseover event, and add index
            // console.log(gets('td')) 
            var tds = gets('td');
            var i = 0;
            for (i = 0; i < tds.length; i++) {
              tds[i].index = i;
              tds[i].onmouseover = function () {
                // Clear td className first
                for (a = 0; a < tds.length; a++) {
                  tds[a].className = '';
                }
                // Modify td className and insert text
                tds[this.index].className = 'td';
                // console.log(i);
                get('p1').innerHTML = (this.index + 1) + arr[this.index];
              }
            }
    
            arr = [
            'Monthly activities: learning programming and English', 'Monthly activities: learning programming and English', 'Monthly activities: learning programming and Japanese', 
            'Monthly activities: learning programming and painting', 'Monthly activities: learning programming and Tourism', 'Monthly activity: learning programming', 
            'Monthly activity: learning programming', 'Monthly activity: learning programming', 'Monthly activity: learning programming', 
            'Monthly activity: learning programming', 'Monthly activity: learning programming', 'Monthly activity: learning programming'
            ]
          }
        </script>
      </head>
      <body>
        <div id="d1">
          <table id="t1">
            <tr>
              <td>1 <br>JAN</td>
              <td>2 <br>FER</td>
              <td>3 <br>MAR</td>
            </tr>
            <tr>
              <td>4 <br>APR</td>
              <td>5 <br>MAY</td>
              <td>6 <br>JUN</td>
            </tr>
            <tr>
              <td>7 <br>JUL</td>
              <td>8 <br>AUG</td>
              <td>9 <br>SEP</td>
            </tr>
            <tr>
              <td>10 <br>OCT</td>
              <td>11 <br>NOV</td>
              <td>12 <br>DEC</td>
            </tr>
          </table>
          <div id="d2">
            <p id="p1">
    
            </p>
          </div>
        </div>
      </body>
    </html>
    

JavaScript Basics

JavaScript composition

  • ECMAScript: interpreter, compiler (almost all compatible)

  • DOM: Document Object Model, HTML, document (mostly compatible)

  • BOM: Browser Object Model,

    window
    

    (totally incompatible)

    • Compatibility of various components and origin of compatibility problems

Variable type

  • Type:

    typeof
    

    operator

    • Usage: the typeof element returns the type of the variable
    • Common types:
      • number, string, boolean, undefined (undefined or undefined), object, function
  • A variable should hold only one type of data

Variable type conversion

  • Data type conversion

    • Example: calculate the sum of two text boxes

    • Explicit type conversion (CAST)

      • parseInt() removes decimals and parseFloat() keeps decimals: extract numbers from left to right and jump out when encountering non numbers

      • Significance and detection of NaN: Not a Number

      • NaN: NaN is not equal to any value, including itself

        • Use isNaN() to detect whether it is all numbers
      • Number() Convert values, String() Convert string, Boolean() Convert Boolean
        
    • Implicit type conversion

      • ==: convert type before comparison

        Comparison = = =: all equal, direct comparison without conversion type

      • -: digital subtraction

        Comparison +: string connection, number addition

      • 5 + null    // Returns 5 because null is converted to 0
        "5" + null  // Return '5null' because null was converted to 'null'
        "5" + 2     // Return 52 because 2 is converted to "2"
        "5" - 2     // Returns 3 because "5" is converted to 5
        "5" * "2"   // Returns 10 because "5" and "2" are converted to 5 and 2
        
  • More methods for converting numeric values to Strings:

    methoddescribe
    toExponential()Returns a string, rounds a number, and writes it using exponential counting.
    toFixed()Returns a string, rounds a number, and writes it with a specified number of decimal places.
    toPrecision()Returns a string and writes a number to the specified length.
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Variable type conversion</title>
        <style></style>
        <script>
          window.onload = function () {
            // Encapsulate getElementById function
            function get(id) {
              return document.getElementById(id);
            }
    
            let t1 = get('t1');
            let t2 = get('t2');
            let b1 = get('b1');
            let s1 = get('s1');
            let s2 = get('s2');
            b1.onclick = function (){
              if (isNaN(t1.value)) {
                s1.innerHTML = '<br>' + t1.value + 'Not a number';
              } else if (isNaN(t2.value)) {
                s1.innerHTML = '<br>' + t2.value + 'Not a number';
              } else {
                console.log('t1:',typeof t1.value, 't2',typeof t2.value);
                let val = parseInt(t1.value) + parseInt(t2.value);
                let val2 = parseFloat(t1.value) + parseFloat(t2.value);
                s1.innerHTML = '<br>int result:' + val+ '<br>float result:' + val2;
                console.log(typeof val);
    
                // ==And - implicit conversion
                let a = t1.value ;
                let b = t2.value;
                if (a == b) {
                  s2.innerHTML = 'a == b' + '<br>a - b = ' + (a - b) + '<br>a + b = ' + (a + b);
                } else if (a === b) {
                  s2.innerHTML = 'a === b!';
                } else {
                  s2.innerHTML = 'a Not equal to b!' + '<br>a - b = ' + (a - b) + '<br>a + b = ' + (a + b);
                }
              }
            }
          }
        </script>
      </head>
      <body>
        <input type="text" name="" id="t1">
        <input type="text" name="" id="t2">
        <input type="button" name="" id="b1" value="calculation">
        <div>
            <span id="s1"></span>
        </div>
        <div>
            <span id="s2"></span>
        </div>
      </body>
    </html>
    

Scope and closure of variables

  • Variable scope (SCOPE)
    • Local variable, global variable
  • What is a closure?
    • A child function can use local variables in the parent function
    • Closures have been used before
    • Definition of closure on the Internet

Naming conventions

  • Naming standard and necessity
    • Readability – able to read
    • Normative – compliance with rules
  • hungarian notation
    • Type prefix + initial capital: getElementByTagName
typeprefixType (English)example
arrayaArrayaItems
Boolean valuebBooleanbIsComplete
Floating point numberfFloatfPrice
functionfnFunctionfnHandler
integeriIntegeriItemCount
objectoObjectoDiv1
regular expression reRegExpreEmailCheck
character stringsStringsUserName
Variant variablevVariantvAnything

operator

  • Arithmetic: + add, - subtract, * multiply, / divide,% modulo

    • Example: interlaced color change, second rotation time
  • Assignment: =, + =, - =, * =, / =,%=

    • +=: i += 1 equals i++
  • Relationship: <, >, < =, > =, = =, = = =, = = =,! ===

    • !== : Different types are not compared and have no results. Only the same type is compared and corresponding===
    • !=: If the types are different, the conversion type will be tried, corresponding to==
  • Logic: & & and, | or! no

    • Example: select all and invert selection
  • Operator precedence: parentheses

  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>operator</title>
        <style>
        .blue {
          width: auto;
          height: 20px;
          background: blue;
        }
        .yellow {
          width: auto;
          height: 20px;
          background: yellow;
        }
        </style>
        <script>
          window.onload = function () {
            // Encapsulate getElementById function
            function get(id) {
              return document.getElementById(id);
            }
            // Encapsulate getElementsByTagName
            function gets(tagName) {
              return document.getElementsByTagName(tagName)
            }
            // Interlaced discoloration
            function liCol() {
              let i = 0;
              let oLi = gets('li') ;
              for (i = 0; i < oLi.length; i++) {
                if (i % 2 === 0) {
                  oLi[i].className = 'blue';
                } else {
                  oLi[i].className = 'yellow';
                }
              }
            }
            liCol();
    
            // Millisecond to date
            const date = Date.now();
            // 60000ms / 1000ms /60s /60m /24h /365d
            const millisecond = date % 1000 + 'millisecond';
            const second = parseInt(date/1000) % 60 + 'second';
            const minute = parseInt(date/1000/60) % 60 + 'branch';
            const hour = parseInt(date/1000/60/60) % 24 + 8 + 'hour';
            const day = parseInt(date/1000/60/60/24/365) % 30 - 9 + 'number';
            const month = parseInt(date/1000/60/60/24/30) % 12 + 4 + 'month'; 
            const year = parseInt(date/1000/60/60/24/265) + 1951 +'year';
            const d1 = get('d1');
            d1.innerHTML = millisecond+ second+ minute+ hour+ day+ month+ year;
          }
    
          // Assignment ` =, + =, - =, * =, / =,% =`
          let i = 11;
          i += 2;
          console.log(i);
          i -= 3;
          console.log(i);
          i *= 2;
          console.log(i);
          i /= 2;
          console.log(i);
          i %= 3;
          console.log(i);
    
          // Judge <, >, < =, > =, = =, = = =, = = =,! ===
          if (i > 0) {
          console.log('i > 0');
          } 
          if (i <= i) {
            console.log('i <= i');
          }
          if (i == '1') {
            console.log('i == "1"')
          }
          if (i === 1) {
            console.log('i === 1')
          }
          if (i != '1') {
            console.log('i != 2')
          }
          if (i !== 1) {
            console.log('i !== 1')
          }
    
          // Logic & & and, | or! no
          if (i<2 && i>0) {
            console.log('i<2 && i>0')
          }
          if (i<2 || i<0) {
            console.log('i<2 || i<0')
          }
        </script>
      </head>
      <body>
        <div>
          <ul>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
          </ul>
        </div>
        <div id="d1"></div>
      </body>
    </html>
    

Program flow control

  • Judgment: if, switch,?:
  • Loop: while, for
  • Jump out: break, continue
  • What is true and what is false
    • stay JavaScript In, truth refers to Boolean value In context, the converted value is a true value. All values are true unless they are defined as False value (that is, all values are true except false, 0, "", null, undefined and NaN).
  • Code: same as below

JSON

  • What is JSON

  • JSON and arrays

  • JSON and for in

  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Program flow control</title>
        <script>
        window.onload = function () {
          // switch
          var i = 0;
          switch (i){
            case i*++i:
              console.log('i');
              break;
            case 1:
              console.log('1')
              break;
            default:
              console.log('default');
              break;
          }
    
          // ?:   Conditions? Statement 1: Statement 2
          var a = 1;
          a % 2 == 0 ? console.log('even numbers'):console.log('singular');
    
          // break continue
          for (i = 0; i < 5; i++){
            if (i === 2){
              // break; //  Interrupt all cycles
              continue; // Interrupt this cycle
            }
            console.log(i);
          }
    
          // json and arrays
          const json = {a: 2, b: 5, c:9};
          const arr = [23, 45, 5467];
          console.log('b:', json.b, 'c:', json['c'], 'No, length', json.length);
          console.log(arr[2], arr.length);
    
          // JSON and for in
          for (var i in arr) {
            console.log('The first' + i + 'Number:' + arr[i]);
          }
          for (var i in json) {
            console.log('The first' + i + 'Number:' + json[i]);
          }
        }
        </script>
      </head>
      <body>
      </body>
    </html>
    

Deep JavaScript

Function return value

  • What is the return value of a function
    • The execution result of the function
    • There can be no return
  • A function should have only one return value type

The function is passed to participate in the inter line style

  • Variable function (indefinite parameter): arguments

    • Is a class array object corresponding to the parameters passed to the function.

    • The arguments object is a local variable available in all (non arrow) functions. You can use the arguments object to refer to the parameters of the function in the function.

    • Functions in JavaScript are different from other object-oriented languages in several ways.

      1. No function overload
      2. There is a class array object arguments that represents a list of arguments

  • Example: summation

    • Sum all parameters
  • Example 2: CSS function

    • Judge arguments length
    • Name the parameter to enhance readability
  • Take non line style (cannot be used to set):

    • obj.currentStyle[attr] is only compatible with IE and returns decimal

    • getComputedStyle(obj, false)[attr], return decimal

    • // Resolve compatibility issues
      // Encapsulates the function to get the calculated element style
      function getStyle(obj, name) {
          if (obj.currentStyle) {
              return obj.currentStyle[name];
          } else {
              return getComputedStyle(obj, '') [name];
          }
      }
      
    • Compound style: background / border should use specific style name, backgroundColor, etc

    • Single style: width / height / position

Array base operation

  • Use of arrays

    • definition
      • var arr = [23, 234, 23, 45];
      • var arr = new Array(12, 5, 7, 34);
      • Without any difference, [] has slightly higher performance because the code is short
  • Array properties

    • length
      
      • It can be obtained and set
      • Example: quick empty array length = 0
  • Use principle of array: only one type of variable should be stored in the array

  • Array method

    • add to
      • Push (element), add from the tail
      • Unshift (element), add from header
    • delete
      • pop(), delete from the tail
      • shift() to delete from the head
  • sort

    • Array sort([comparison function]) sorts an array. Only the array can be used

      • Sort a string array without comparison function. It is sorted by ASCII code by default

      • Sort an array of numbers, add numbers, and compare the size function

      • // Positive order comparison function number size character size ASCII value size
        function positiveSort(n1, n2) {
            if (isNaN) {
                if (n1 > n2) {
                    return 1;
                }
                if (n1 < n2) {
                    return -1;
                }
                if (n1 === n2) {
                    return 0;
                }
            } else {
                return n1 - n2;
            }
        }
        
  • Conversion class

    • array.concat(Array 2)
      
      • Connects two arrays that can be used for deep replication
    • array.join(Separator)
      
      • Replace the array with the specified separator, and recombine the array elements to generate a string
      • String split
    • array.reverse()
      
      • Invert the order of the elements in the array
  • Array slice(start,end)

    • Returns the selected element from an existing array, which can be used for deep replication
    • When start is negative, add it to the length of the array and then find it
  • splice: delete first, then insert

  • Array Splice (start point, length, element)

  • delete

    • Array Splace (start point, length)
  • insert

    • Array Splice (start point, 0, element...)
  • replace

    • Array Splice (start point, length, element)
  • ECMAScript two methods about location

    • arrayObject.indexOf(searchvalue,startIndex)
      
      • Search backward from startIndex, and the default value is 0
      • Return number to find the position of the item in the array. If it is not found, return - 1
    • ``arrayObject.lastIndexOf(searchvalue,startIndex)`

      • Search forward from startIndex. The default value is 0
      • Return number to find the position of the item in the array. If it is not found, return - 1
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Array operation</title>
        <style>
        div {
          margin-top: 10px;
        }
        </style>
        <script>
        var arr = [23, 435, 567, 321, 9, 4];
        var arr2 = new Array('m', 'r', 'a', 'z', 'c', 'p', 'e', 'Broken', 'No hair');
    
        // Encapsulate getById
        function get(id) {
          return document.getElementById(id);
        }
    
        window.onload = function () {
          // Display array
          function showArr() {
            get('d1').innerHTML = arr + ' + ' + arr2;
          }
          showArr();
    
          // Add element add from tail
          get('btn2').onclick = function () {
            arr.push(222);
            showArr();
          }
    
          // Add element add from header
          get('btn22').onclick = function () {
            arr.unshift(234);
            showArr();
          }
    
          // Delete element delete from tail
          get('btn3').onclick = function () {
            arr.pop();
            showArr();
          }
    
          // Delete element delete from header
          get('btn33').onclick = function () {
            arr.shift();
            showArr();
          }
    
          // Sort element
          get('btn4').onclick = function () {
            arr.sort(positiveSort);
            arr2.sort(positiveSort);
            showArr();
          }
          // Compare function number size to character size to ASCII value size
          function positiveSort(n1, n2) {
            if (isNaN) {
              if (n1 > n2) {
                return 1;
              }
              if (n1 < n2) {
                return -1;
              }
              if (n1 === n2) {
                return 0;
              }
            } else {
              return n1 - n2;
            }
          }
    
          // Splice array
          get('btn5').onclick = function () {
            arr = arr.concat(arr2);
            showArr();
          }
          
          // Separator
          get('btn6').onclick = function () {
            arr = arr.join('_');
            showArr();
          }
          
          // Splice insert splice (start point, length, element)
          get('btn7').onclick = function () {
            arr.splice(2, 0, 5, 1);
            showArr();
          }
          // splice delete
          get('btn8').onclick = function () {
            arr.splice(0, arr.length);
            showArr();
          }
          // splice replace = delete + insert
          get('btn9').onclick = function () {
            arr.splice(2, 1, 999, 888);
            showArr();
          }
    
        }
        </script>
      </head>
      <body>
        <div>
          <input type="button" name="" id="btn2" value="Add element to tail">
          <input type="button" name="" id="btn22" value="Add element to header">
          <input type="button" name="" id="btn3" value="Tail delete element">
          <input type="button" name="" id="btn33" value="Header delete element">
          <input type="button" name="" id="btn4" value="Positive sort elements">
        </div>
        <div>
          <input type="button" name="" id="btn5" value="Splice array">
          <input type="button" name="" id="btn6" value="Split array">
        </div>
        <div>
          <input type="button" name="" id="btn7" value="Insert element">
          <input type="button" name="" id="btn8" value="Delete element">
          <input type="button" name="" id="btn9" value="Replace element">
        </div>
        <div id="d1"></div>
      </body>
    </html>
    
  • Array name as variable (traversing the array in the array):

    var arr1=new Array(); 
    var arr2=new  Array(); 
    var arrlist= new Array(); //Store the above array
    arrlist.push(arr1);
    arrlist.push(arr2);
    //Loop through arrlist, you can achieve the effect you want
    

Use of timer

Function of timer

  • Turn on the timer

    • Setinterval (function, interval time) interval type. The function cannot be followed by parentheses and parameters

    • SetTimeout (function, delay time) delay type

      1. If the execution time of the current task is too long, the execution of the expiration timer task will be delayed
      2. this environment in the callback function set with setTimeout does not point to the callback function
      3. For inactive pages, the minimum interval between settimeouts is 1000 milliseconds
      4. There is a nested call problem in setTimeout. After more than 5 calls, the system will set the minimum execution time interval to 4 milliseconds
      5. The delay execution time has a maximum value
    • Web Workers is a javascript multithreading solution provided by HTML5. It can run some large amount of code by Web Workers without freezing the user interface.

      Note: Web Workers require browser support from IE10 and above.

    • The difference between the two timers is window Onload is executed one second later

  • Stop Timer

    • Clearinterval (timer name)
    • Cleartimeout (timer name)
  • code:

    window.onload = function () {
    	var oBtn1 = document.getElementById('btn1');
    	var oBtn2 = document.getElementById('btn2');
        var timer = null;
        
        oBtn1.onclick = function () {
    		timer = setInterval(function () {
                alert('a');
            }, 2000);
        };
        
        oBtn2.onclick = function () {
            clearInterval(timer);
        };
    };
    

Digital clock

  • Effect idea

  • get SysTime

    • new Date object
    • getHours / getMinutes / getSeconds
  • display system time

    • String connection
    • Null filling
  • Set picture path

    • str[i]: fetch the ith value in the string, incompatible ie7
  • charAt(i) method: get the ith value in the string, which is compatible with various browsers

  • Set path: "url('img/0.png ')"

  • String operation method in JavaScript

    • obj.charAt(index)
      
      • Returns the character of the index position
    • obj.charCodeAt()
      
      • Returns the character encoding of the index position
    • obj.indexOf("str")
      
      • Search str sequentially and return its location. If not found, return - 1
    • obj.lastIndexOf("str")
      
      • Search str in reverse order and return its location. If not found, return - 1
    • slice(start,end): same as array

    • substring(start,end): the same as above. The difference is that when the parameter is negative, it is automatically converted to 0, and the smaller number is the starting bit

    • substr(start,len): the same as above. Len indicates the length of interception

  • code:

    <!DOCTYPE html>
    <html>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
      <title>Digital clock</title>
      <style>
      body{
        margin: 0;
        padding: 0;
        background-color: rgb(49, 49, 49);
      }
      li {
        list-style: none;
        float: left;
        width: 100px;
        height: 149px;
      }
      span {
        float: left;
        font-size: 100px;
        color: rgb(255, 255, 255);
      }
      </style>
      <script>
      window.onload = function () {
        // Encapsulate getElementsByTagName
        function gets(tagName) {
          return document.getElementsByTagName(tagName)
        }
    
        // Digital clock
        // Digital clock picture setting function
        const oLi = gets('li');
        function clock() {
          const date = new Date();
          const str = addZero(date.getHours()) + addZero(date.getMinutes()) + addZero(date.getSeconds());
        
          let i = 0;
          for (i = 0; i < oLi.length; i++) {
            oLi[i].style.backgroundImage = "url('img/"+ str.charAt(i) +".png')";
          }
        }
        // Zero filling
        function addZero(num) {
          if (num < 10) {
            num = '0' + num;
          } else {
            num = '' + num;
          }
          return num;
        }
        // If you execute it first, there will be no blank for one second. The timer needs window Onload is executed one second later
        clock();
        // The timer refreshes once per second
        setInterval(clock, 1000);
      }
      </script>
      <body>
        <ul>
          <li></li>
          <li></li>
          <span>:</span>
          <li></li>
          <li></li>
          <span>:</span>
          <li></li>
          <li></li>
        </ul>
      </body>
    </html>
    

Other methods of Date object

methoddescribe
getDate()Obtain days in numerical terms (1-31)
getDay()Or weeks in numerical terms (0-6)
getFullYear()Year of four places (yyyy)
getHours()When obtained (0-23)
getMilliseconds()Get milliseconds (0-999)
getMinutes()Get minutes (0-59)
getMonth()Gain month (0-11)
getSeconds()Get seconds (0-59)
getTime()Acquisition time (milliseconds since January 1, 1970)

Delay prompt box

  • Effect demonstration
  • Original method
    • Move in show out hide
  • Move out delay hiding
    • After moving into the following div, it is still hidden
  • Simplified code
    • Merge two identical mouseover and mouseout
    • Two consecutive events a=b=c=function() share a function
  • Code: same as below

Seamless rolling

  • Effect demonstration

  • Fundamentals of object motion

    • Let the div move
    • offsetLeft/offsetTop: get the left margin / top margin of the current object
    • offsetWidth/offsetHeight
    • Use the timer to move the object continuously:
      • innerHTML splices two pictures, and px is added after the width to take effect
      • overflow:hidden; Hide content outside elements
  • Change the direction of scrolling

    • Modify speed
    • Modify judgment conditions
    • Multiple clicks are faster and faster: if (!timer) or clearInterval(timer); Avoid repeated calls
  • Mouse in pause

    • Move in close timer
    • Remove restart timer
  • code:

    <!DOCTYPE html>
    <html>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
      <link rel="stylesheet" href="../reset.css">
      <title>Move out delay hiding</title>
      <style>
        body {
          width: 560px;
          margin: 0 auto;
        }
        #d2 {
          margin: 10px;
          width: 200px;
          height: 200px;
          background-color: rgb(0, 204, 255);
          display: none;
          float: left;
        }
        #d1 {
          margin: 10px;
          width: 100px;
          height: 100px;
          background-color: rgb(0, 255, 149);
          float: left;
        }
        #d3 {
          margin: 220px auto;
          width: 560px;
          height: 140px;
          position: absolute;
          background-color: rgb(135, 182, 182);
          overflow: hidden;
        }
        #u1 {
          position: relative;
        }
        #u1 li {
          float: left;
        }
      </style>
      <script>
      window.onload = function () {
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
        // Encapsulate getElementsByTagName
        function gets(tagName) {
          return document.getElementsByTagName(tagName)
        }
    
        // Move the mouse over d1, d2 will be displayed and moved out of hiding;
        // Move the mouse over d2, clear the timer, move out d2 and start the timer
        let timer = '';
        get('d1').onmouseover= get('d2').onmouseover = function () {
          clearTimeout(timer);
          get('d2').style.display = 'block';
        }
        get('d1').onmouseout= get('d2').onmouseout = function () {
          timer = setTimeout(hide,1000);
        }
        function hide() {
          get('d2').style.display = 'none';
        }
    
        // Seamless rolling
        get('u1').innerHTML += get('u1').innerHTML;
        get('u1').style.width = gets('li').length * gets('li')[0].offsetWidth + 'px';
        let timer2 = '';
        let speed = 2;
        // Shift left
        get('btn1').onclick = function () {
          speed = -2;
          if (!timer2) {
            timer2 = setInterval(move, 30);
          }
        }
        // Shift right
        get('btn2').onclick = function () {
          speed = 2;
          if (!timer2) {
            timer2 = setInterval(move, 30);
          }
        }
        // move
        function move() {
          get('u1').style.left = get('u1').offsetLeft + speed + 'px';
          if (get('u1').offsetLeft < -get('u1').offsetWidth/2) {
            get('u1').style.left = 0;
          } else if (get('u1').offsetLeft > 0){
            get('u1').style.left = -get('u1').offsetWidth/2 + 'px';
          }
            console.log(get('u1').offsetLeft);
        }
        // Mouse over
        get('d3').onmouseover = function () {
          clearInterval(timer2);
        }
        get('d3').onmouseout = function () {
          timer2 = setInterval(move, 30);
        }
      }
      </script>
      <body>
        <div id="d1"></div>
        <div id="d2"></div>
        <div id="d3">
          <ul id="u1">
            <li><img src="images/1.png" alt=""></li>
            <li><img src="images/2.png" alt=""></li>
            <li><img src="images/3.png" alt=""></li>
            <li><img src="images/4.png" alt=""></li>
          </ul>
        </div>
        <input type="button" name="" id="btn1" value="Shift left">
        <input type="button" name="" id="btn2" value="Shift right">
      </body>
    </html>
    

DOM Foundation

DOM Foundation

  • What is DOM
  • Browser support

DOM node

  • DOM node

    • Get child nodes

      • childNodes
        

        Incompatible with higher version, use:

        nodeType
        

        compatible

        • Get text node (nodeType == 3) and element node (nodeType == 1)
      • children: only get element nodes, compatible

    • parentNode
      

      : find parent node

      • Example: click the link to hide the whole li
    • offsetParent
      

      : find locate parent

      • Example: get the actual position of the element on the page
    • First and last child nodes

      • firstChild has compatibility problems. IE6-8 is used
      • firstElementChild later
      • lastChild/ lastElementChild
    • Sibling node

      • There is a compatibility problem. IE6-8 uses the previous one
      • nextSbling / nextElementSibling
      • previousSibling/ previousElementSibling

Action element properties

  • Action element properties
    • Element attribute operation
      • First: odiv style. display = 'block';
      • Second: odiv style['display'] = 'block';
      • Third: Dom mode
    • Dom mode operation element attribute
      • Get: getattribute (name)
      • Setting: setAttribute (name, value)
      • Delete: removeattribute (name)

Flexible search of DOM elements

  • Select elements with className

    • How to select elements with className

      • Select all elements
      • Filter by className criteria
    • Encapsulated as a function:

      // Find elements by className
      function getByClass(oParent, sClass) {
      	var aResult = [];
      	var aEle = oParent.getElementsByTagName('*');
      	
      	for(var i = 0; i < aEle.length; i++) {
              if (aEle[i].className == sClass) {
                  aResult.push(aEle[i]);
              }
          }
          return aResult;
      }
      

DOM operation application

Create, insert, and delete elements

  • Create a DOM element

    • document. CreateElement (tag name) creates a node without rendering

    • Parent.appendChild(node)
      

      Delete the original child node

      , add child nodes, and render

      • Example: insert li for ul
  • Insert element

    • Parent.insertBefore(node, Original node)
      

      Insert before existing element

      • Example: flashback insert li
  • Delete DOM element

    • Parent.removeChild(node)
      

      Delete a node

      • Example: delete li
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>DOM Create insert delete element</title>
        <script>
          window.onload = function () {
            // Encapsulate getElementById
            function get(id) {
              return document.getElementById(id);
            };
    
            // Add li under ul
            let oUl = get('u1');
            get('btn1').onclick = function () {
              let oLi = document.createElement('li');
              let sL = get('txt1').value + "<a href='javascript:;'>delete</a>";
              oLi.innerHTML = sL;
              oUl.appendChild(oLi);
              aRemove();
            };
            // Insert li from ul
            get('btn2').onclick = function () {
              let oLi = document.createElement('li');
              let aLi = document.getElementsByTagName('li');
              let sL = get('txt1').value + "<a href='javascript:;'>delete</a>";
              let i = get('txt2').value - 1;
              oLi.innerHTML = sL;
              if (aLi.length > i && aLi.length > 0) {
                oUl.insertBefore(oLi, aLi[i]);
              } else {
                oUl.appendChild(oLi);
              }
              aRemove();
            };
            // Delete li from ul
            get('btn3').onclick = function () {
              let aLi = document.getElementsByTagName('li');
              let i = get('txt2').value - 1;
              if (i < aLi.length && i >= 0) {
               oUl.removeChild(aLi[i]);
              } else {
                alert('Could not find page'+ (parseInt(i) + 1) +'individual li');
              }
            };
    
            // this deletes li from ul
            function aRemove() {
              let aA = document.getElementsByTagName('a');
              let i =0
              for (i = 0; i < aA.length; i++) {
                aA[i].onclick = function () {
                  oUl.removeChild(this.parentNode);
                }
              }
            }
          }
        </script>
      </head>
      <body>
        <input type="text" name="" id="txt1" value="123">
        <input type="button" name="" id="btn1" value="increase">
        <input type="text" name="" id="txt2" value="1">
        <input type="button" name="" id="btn2" value="insert">
        <input type="button" name="" id="btn3" value="delete">
        <div is="d1">
          <ul id="u1">
          </ul>
        </div>
      </body>
    </html>
    

Document fragment

  • Document fragmentation can theoretically improve the performance of DOM operations

  • Document fragmentation principle

  • document.createDocumentFragment(): Vue, MVVM, and

  • code:

    var element  = document.getElementById('ul'); // assuming ul exists
    var fragment = document.createDocumentFragment();
    var browsers = ['Firefox', 'Chrome', 'Opera', 
        'Safari', 'Internet Explorer'];
    
    browsers.forEach(function(browser) {
        var li = document.createElement('li');
        li.textContent = browser;
        fragment.appendChild(li);
    });
    
    element.appendChild(fragment);
    

DOM operation application advanced

Table label

formdescribe
<table>Define table
<caption>Defines the table title.
<th>Defines the header of the table.
<tr>Define the rows of the table.
<td>Define table cells.
<thead>Defines the header of the table.
<tbody>Defines the body of the table.
<tfoot>Defines the footer of the table.
<col>Defines the attributes used for table columns.
<colgroup>Defines the group of table columns.

Table application

  • obtain

    • tBodies / tHead / tFoot / rows / cells

      var oTab = document.getElementById('tab1');
      alert(oTab.tBodies[0].rows[1].cells[1].innerHTML);
      
  • Interlaced discoloration

    • Mouse in highlight
  • Add / delete a row

    • Use of DOM methods
  • search

    • Version 1: base version - string comparison
    • Version 2: ignore case - case conversion tolower case() / touppercase(), return string
    • Version 3: fuzzy search - the use of search(). If it is not found, it returns - 1. If it is found, it returns the location
    • Version 4: multi keyword – split() splits a string and returns an array
    • Highlight, filter
  • sort

    • Move li and use appendChild(): delete the original li and add a new li at the end
    • Element sorting: convert element collection to array – sort() sort – appendChild() insert
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Table operation</title>
        <style>
          body {
            margin: 0 auto;
            width: 400px;
          }
          table {
            border: rgb(97, 97, 97) 1px solid;
            width: 400px;
          }
          td {
            border: rgb(255, 106, 136) 1px solid;
          }
        </style>
        <script>
          window.onload = function () { 
            // Encapsulate getElementById
            function get(id) {
              return document.getElementById(id);
            };
    
            // Tabular data
            // Tthead is passed in as the last array
            var data = new Array(
              [1, 'Zhang San', 12, "<a href='javascript:;'>delete</a>"],
              [2, 'Li Si', 13, "<a href='javascript:;'>delete</a>"],
              [3, 'Wang Wu', 14, "<a href='javascript:;'>delete</a>"],
              [4, 'Wang Qi', 19, "<a href='javascript:;'>delete</a>"],
              [5, 'Wang Jiu', 24, "<a href='javascript:;'>delete</a>"],
              [6, 'Li Liu', 42, "<a href='javascript:;'>delete</a>"],
              [7, 'Li San', 23, "<a href='javascript:;'>delete</a>"],
              [8, 'Li Liu', 76, "<a href='javascript:;'>delete</a>"],
              [9, 'CAT', 8, "<a href='javascript:;'>delete</a>"],
              [10, 'cat', 2, "<a href='javascript:;'>delete</a>"],
              [11, 'dog', 1, "<a href='javascript:;'>delete</a>"],
              [12, '3', 5, "<a href='javascript:;'>delete</a>"],
              [13, '31', 2, "<a href='javascript:;'>delete</a>"],
              [14, '4', 7, "<a href='javascript:;'>delete</a>"],
              [15, '42', 9, "<a href='javascript:;'>delete</a>"],
              [16, 'ah Q', 9, "<a href='javascript:;'>delete</a>"],
              ['ID', 'full name', 'Age', "operation"]
            );
    
            // Pass in the formatted array file data and automatically generate the table
            function createTable(data) {
              // Use document fragments to generate tables
              // var frag = document.createDocumentFragment();
              var table = document.createElement('table');
              var caption = document.createElement('caption');
              var thead = document.createElement('thead');
              var tbody = document.createElement('tbody');
              var tr = document.createElement('tr');
              // Render table
              get('b1').appendChild(table);
              table.appendChild(caption);
              table.appendChild(thead);
              table.appendChild(tbody);
              thead.appendChild(tr);
              var oTr = document.getElementsByTagName('tr');
              // Render cells
              caption.innerHTML = "<strong style='font-size: 20px'>Personnel table</strong>";
              var i = 0;
              var j = 0;
              var rNmb = data.length - 1; // that 's ok
              var rLth = data[0].length;  //column
              // Generate header
              for (i = 0; i < rLth; i++){
                var th = document.createElement('th');
                oTr[0].appendChild(th);
                // Write th data
                var aArr = data[rNmb];
                table.tHead.rows[0].cells[i].innerHTML = aArr[i];
              }
              // Generate tbody and insert content
              for (i = 0; i < rNmb; i++) {
                var tr = document.createElement('tr');
                tbody.appendChild(tr);
                for (j = 0; j < rLth; j++) {
                  var td = document.createElement('td');
                  tr.appendChild(td);
                  // Write td data
                  aArr = data[i];
                  table.tBodies[0].rows[i].cells[j].innerHTML = aArr[j];
                }
              }
              // If you don't add tBodies[0], you will treat thad as a line
              // console.log(table.rows.length); 
              chgColor();
              aClick();
            }
            createTable(data);
    
            function chgColor() {
              // Interlaced discoloration
              var oTr = document.getElementsByTagName('tr');
              var oldColor = '';
              for (i = 1; i < oTr.length; i++) {
                if (i % 2 === 0) {
                  oTr[i].style.background = '#eee';
                } else {
                  oTr[i].style.background = '#bbb';
                }
                // Mouse in highlight
                oTr[i].onmouseover = function () {
                  oldColor = this.style.background;
                  this.style.background = 'yellow';
                }
                oTr[i].onmouseout = function () {
                  this.style.background = oldColor;
                }
              }
            }
    
            // Add / delete a row 
            var btn1 = get('btn1');
            var btn2 = get('btn2');
            var btn3 = get('btn3');
            var btn4 = get('btn4');
            var btn5 = get('btn5');
            var btn6 = get('btn6');
            var txt1 = get('txt1');
            var txt2 = get('txt2');
            var txt3 = get('txt3');
            var txt4 = get('txt4');
            var id = data.length;
            var oTab = document.getElementsByTagName('table');
            // txt1 txt2 add one line
            btn1.onclick = function () {
              if (txt1.value != '' && txt2.value != '') {
                var newPerson = new Array(id, txt1.value, txt2.value, "<a href='javascript:;'>delete</a>")
                data.splice(data.length - 1, 0, newPerson);
                get('b1').removeChild(oTab[0]);
                createTable(data);
                id++;
              } else {
                alert('Please enter your name and age!');
              }
            }
            // Delete a row according to txt4
            btn3.onclick = del;
            function del() {
              for (var i in data) {
                var aData = data[i];
                // console.log(aData[0])
                // Verify that the input ID matches the data ID match
                if (aData[0] === parseInt(txt4.value) || aData[0] === parseInt(txtTd)) {
                  data.splice(i, 1);
                  break;
                }
              }
              get('b1').removeChild(oTab[0]);
              createTable(data);
            }
    
            // Registration a tag deletion event
            var txtTd = '';
            function aClick() {
              var oA = document.getElementsByTagName('a');
              for (var i in oA) {
                oA[i].onclick = function () {
                  // oTab[0].tBodies[0].removeChild(this.parentNode.parentNode);
                  txtTd = this.parentNode.parentNode.cells[0].innerHTML;
                  del();
                }
              }
            }
    
            // data filter query
            btn2.onclick = searchTr;
            function searchTr() {
              var oTr = document.getElementsByTagName('tr');
              var bData = new Array();
              // Save header
              var thData = data[data.length-1];
              if (txt3.value != '') {
                for (var i in data) {
                  var aData = data[i];
                  // console.log(aData[0])
                  // Verify whether the input name and data Name match
                  if (aData[1].toLowerCase() === txt3.value.toLowerCase()) {
                    // ignore case
                    bData.push(data[i]);
                  } else if (aData[1].toLowerCase().search(txt3.value.toLowerCase()) != -1) {
                    // Fuzzy search()
                    bData.push(data[i]);
                  } else {
                    // Multi keyword search split
                    var aTxt = txt3.value.split(' ');
                    for(var j in aTxt) {
                      if (aData[1].toLowerCase().search(aTxt[j].toLowerCase()) != -1) {
                        bData.push(data[i]);
                        continue;
                      }
                    }
                  }
                }
              // Incoming header thData
              bData.push(thData);
              get('b1').removeChild(oTab[0]);
              createTable(bData);
              } else {
                back();
              }
            }
    
            // Recover data
            btn4.onclick = back;
            function back() {
              get('b1').removeChild(oTab[0]);
              createTable(data);
            }
    
            // tr highlight query
            btn5.onclick = function () {
              chgColor();
              var name = '';
              for (i = 0; i < oTab[0].tBodies[0].rows.length; i++) {
                name = oTab[0].tBodies[0].rows[i].cells[1].innerHTML; 
                if (txt3.value != '') {
                  if (name.toLowerCase() === txt3.value.toLowerCase()) {
                    // ignore case
                    oTab[0].tBodies[0].rows[i].style.background = 'yellow';
                  } else if (name.toLowerCase().search(txt3.value.toLowerCase()) != -1) {
                    // Fuzzy search()
                    oTab[0].tBodies[0].rows[i].style.background = 'yellow';
                  } else {
                    // Multi keyword search split
                    var aTxt = txt3.value.split(' ');
                    for(var j in aTxt) {
                      if (name.toLowerCase().search(aTxt[j].toLowerCase()) != -1) {
                        oTab[0].tBodies[0].rows[i].style.background = 'yellow';
                        continue;
                      }
                    }
                  }
                } else {
                  back();
                }
              }
            }
    
            // sort() method by data element
            btn6.onclick = sortName;
            var item = 0; // Sorted elements
            var txt5 = get('txt5');
            var thData = data[data.length-1]; // Save th
            function sortName() {
              item = parseInt(txt5.value);
              data.pop(); // Remove the last th
              data.sort(compare); // Forward sort
              data.push(thData); // th add it back
              back(); //Generate table
            }
            // Comparison function the numeric type and string type of this function cannot be mixed
            function compare(arr1, arr2) {
              var val1 = arr1[item];
              var val2 = arr2[item];
              if (!isNaN(val1) && !isNaN(val2)) {
                return val1 - val2;
              } else {
                if (val1 > val2) {
                  return 1;
                } else if (val1 < val2) {
                  return -1;
                } else if (val1 === val2) {
                  return 0;
                }
              }
            }
          }
        </script>
      </head>
      <body id="b1">
        <div>
          <input type="text" name="name" id="txt1" placeholder="full name">
          <input type="text" name="age" id="txt2" placeholder="Age">
          <input type="button" name="" id="btn1" value="increase">
        </div>
        <div>
          <input type="text" name="" id="txt3" value="Zhang 365">
          <input type="button" name="" id="btn2" value="Filter query">
          <input type="button" name="" id="btn4" value="return">
          <input type="button" name="" id="btn5" value="Highlight query">
        </div>
        <div>
          <input type="text" name="" id="txt4" placeholder="id">
          <input type="button" name="" id="btn3" value="delete">
        </div>
        <div>
          <input type="text" name="" id="txt5" value='1'>
          <input type="button" name="" id="btn6" value="sort">
        </div>
      </body>
    </html>
    

Form application

  • Basic knowledge of forms (described in detail when learning events in this chapter)
    • What is a form
      • Submit data to the server, such as user registration
    • action: where to submit
  • Form Events
    • onsubmit: occurs when submitting
    • onreset: occurs during reset
  • Form content validation
    • Prevent users from entering illegal characters: block event
    • Verification on input and loss of focus: onkeyup and onblur
    • Check on submission: onsubmit
    • Background data check

JS Sports Foundation

Sports Foundation

  • Let the div move
  • Speed: how fast an object moves
  • Bug s in motion
    • Will not stop
    • Some values of speed will not stop
    • Click to move after reaching the position
    • Repeated clicks speed up
  • Uniform motion
    • Constant speed

Motion frame and its application

  • Motion frame

    • At the beginning of the movement, turn off the existing timer
    • Separate movement from stop: if / else
  • Motion frame instance

    • Example 1: share to sidebar
      • Calculate the speed value through the target point
    • Example 2: fade in and out pictures
      • Storing transparency with variables
      • filter:alpha(opacity=30); opacity: 0.3; IE uses the former
  • <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Motion frame and its application</title>
        <style>
          #div1 {
            width: 150px;
            height: 400px;
            background-color:cyan;
            position: absolute;
            left: -150px;
          }
          #div1 span {
            width: 20px;
            height: 60px;
            left: 150px;
            background-color:rgb(106, 176, 255);
            position: absolute;
            margin-top: 170px;
          }
          #div2 {
            left: 200px;
            position: absolute;
            filter:alpha(opacity=30);
            opacity: 0.3;
          }
        </style>
        <script>
          window.onload = function () {
            // Encapsulate getElementById
            function get(id) {
              return document.getElementById(id);
            };
    
            var oDiv = get('div1');
            var timer = '';
            var speed = 0;
            var target = 0;
            // Motion frame
            function startMove(target) {
              clearInterval(timer);
              timer = setInterval(move, 30);
              function move() {
                if (oDiv.offsetLeft < target) {
                  speed = 10;
                  oDiv.style.left = oDiv.offsetLeft + speed + 'px';
                } else if (oDiv.offsetLeft > target) {
                  speed = -10;
                  oDiv.style.left = oDiv.offsetLeft + speed + 'px';
                } else if (oDiv.offsetLeft === target){
                  clearInterval(timer);
                }
              }
            }
            // Register mouse in event
            oDiv.onmouseover = function () {
              startMove(0);
            };
            oDiv.onmouseout = function () {
              startMove(-150);
            };
    
            // Picture fade in and out
            var oDiv2 = get('div2');
            var alpha = 30;
            oDiv2.onmouseover = function () {
              shallow(100);
            }
            oDiv2.onmouseout = function () {
              shallow(30);
            }
            function shallow(target) {
              clearInterval(timer);
              timer = setInterval(shallowMove, 30);
              function shallowMove() {
                if (alpha === target) {
                  clearInterval(timer);
                } else if (alpha < target) {
                  speed = 10;
                  alpha += speed;
                  oDiv2.style.filter = 'alpha(opacity='+ alpha +')';
                  oDiv2.style.opacity = alpha/100;
                } else if (alpha > target) {
                  speed = -10;
                  alpha += speed;
                  oDiv2.style.filter = 'alpha(opacity='+ alpha +')';
                  oDiv2.style.opacity = alpha/100;
                }
              }
            }
          }
        </script>
      </head>
      <body>
        <div id="div1">
          <span>Share to</span>
        </div>
        <div id="div2"><img src="images/0.png" alt=""></div>
      </body>
    </html>
    

Buffer motion

  • Gradually slow down and finally stop

  • The greater the distance, the greater the speed, and the speed is rounded

    • Speed is determined by distance
    • Speed = (target value - current value) / scaling factor
    • Math.ceil: round up
    • Math.floor: round down
  • Example: buffer menu

    • Bug: speed rounding math ceil,Math.floor

    • Buffer sidebar that follows page scrolling

      • Potential problem: when the target is not an integer
      • Target rounding: parseInt()
    • scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      
      • document.documentElement.scrollTop: IE,Firefox
      • document.body.scrollTop: chrome
  • Math.random()

    • Returns a random floating-point number equal to 0 and less than 1

    • Note: find the distance between n and m

      Formula of random integer

      • random = Math.floor(Math.random()*(m-n+1)+n)
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <link rel="stylesheet" href="../reset.css">
        <title>Buffer movement and stop conditions</title>
        <style>
          body {
            width: 800px;
            height: 2000px;
          }
          #div1 {
            width: 150px;
            height: 400px;
            background-color:cyan;
            position: absolute;
            left: -150px;
          }
          #div1 span {
            width: 20px;
            height: 60px;
            left: 150px;
            background-color:rgb(106, 176, 255);
            position: absolute;
            margin-top: 170px;
          }
          #div2 {
            top: 50px;
            left: 150px;
            position: absolute;
            filter:alpha(opacity=30);
            opacity: 0.3;
            width: 140px;
            height: 140px;
            background-color: red;
          }
          #div3 {
            width: 100px;
            height: 200px;
            background: rgb(99, 128, 255);
            position: absolute;
            right: 0px;
            bottom: 0px;
          }
          #div4 {
            width: 298px;
            height: 198px;
            border: rgb(0, 0, 0) solid 1px;
            position: absolute;
            left: 100px;
          }
        </style>
        <script>
          window.onload = function () {
            // Encapsulate getElementById
            function get(id) {
              return document.getElementById(id);
            };
    
            var oDiv = get('div1');
            var timer = '';
    
            // Register mouse in event
            oDiv.onmouseover = function () {
              startMove(0, oDiv);
            };
            oDiv.onmouseout = function () {
              startMove(-150, oDiv);
            };
    
            // Picture fade in and out
            var oDiv2 = get('div2');
            var alpha = 30;
            oDiv2.onmouseover = function () {
              shallow(100);
            }
            oDiv2.onmouseout = function () {
              shallow(30);
            }
            // Shallower function
            function shallow(target) {
              clearInterval(timer);
              timer = setInterval(shallowMove, 30);
              function shallowMove() {
                speed = (target - alpha)/7;
                if (alpha === target) {
                  clearInterval(timer);
                } else if (alpha < target) {
                  alpha += speed;
                  oDiv2.style.filter = 'alpha(opacity='+ Math.ceil(alpha) +')';
                  oDiv2.style.opacity = Math.ceil(alpha)/100;
                } else if (alpha > target) {
                  alpha += speed;
                  oDiv2.style.filter = 'alpha(opacity='+ Math.floor(alpha) +')';
                  oDiv2.style.opacity = Math.floor(alpha)/100;
                }
              }
            }
    
            // Buffer sidebar that follows page scrolling
    
            var oDiv3 = get('div3'); 
            window.onscroll = function () {
              var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
              var target = parseInt((document.documentElement.clientHeight - oDiv3.offsetHeight)/2 + scrollTop);
              scrollMove(target);
              console.log(
                'Viewing area:', document.documentElement.clientHeight,
                'Rolling distance:', scrollTop, 
                'div3 Height of:', oDiv3.offsetHeight, 
                'Target value:', target) 
            }
            // Longitudinal motion function
            function scrollMove(target) {
              clearInterval(timer);
              timer = setInterval(scrollMoving, 30);
    
              function scrollMoving() {
                var speed = (target - oDiv3.offsetTop)/7;
                if (oDiv3.offsetTop === target) {
                  clearInterval(timer);
                } else if (oDiv3.offsetTop > target) {
                  oDiv3.style.top = oDiv3.offsetTop + Math.floor(speed) + 'px';
                } else if (oDiv3.offsetTop < target) {
                  oDiv3.style.top = oDiv3.offsetTop + Math.ceil(speed) + 'px';
                }
              }
            }
    
            // Conditions for motion stop
            var btn1 = get('btn1');
            var btn2 = get('btn2');
            var btn3 = get('btn3');
            var btn4 = get('btn4');
            btn1.onclick = function () {
              startMove(100, oDiv2);
            }
            btn2.onclick = function () {
              startMove(400, oDiv2);
            }
            btn3.onclick = function () {
              startMove2(100, oDiv2);
            }
            btn4.onclick = function () {
              startMove2(400, oDiv2);
            }
            // Lateral buffer motion frame
            function startMove(target, div) {
              clearInterval(timer);
              timer = setInterval(move, 30);
              function move() {
                speed = (target - div.offsetLeft)/9;
                if (div.offsetLeft < target) {
                  div.style.left = div.offsetLeft + Math.ceil(speed) + 'px';
                } else if (div.offsetLeft > target) {
                  div.style.left = div.offsetLeft + Math.floor(speed) + 'px';
                } else if (div.offsetLeft === target){
                  clearInterval(timer);
                }
              }
            }
            // Transverse uniform motion frame
            function startMove2(target, div) {
              clearInterval(timer);
              timer = setInterval(move2, 30);
              function move2() {
                // speed forward
                if (div.offsetLeft <= target) {
                  speed = 9;
                  moving();
                }
                // speed reverse
                else if (div.offsetLeft >= target) {
                  speed = -9;
                  moving();
                } 
                function moving() {
                  if (Math.abs(target - div.offsetLeft) <= Math.abs(speed)) {
                    div.style.left = target + 'px'; // Direct arrival
                    clearInterval(timer); // stop it
                  } else {
                    div.style.left = div.offsetLeft + speed + 'px';
                  }
                }
              }
            }
          }
        </script>
      </head>
      <body>
        <div id="div1">
          <span>Share to</span>
        </div>
        <div id="div2"><img src="images/0.png" alt=""></div>
        <div id="div3"></div>
        <div id="div4">
          <input type="button" name="" id="btn1" value="Slow down to 100 px">
          <input type="button" name="" id="btn2" value="Slow down to 400 px">
          <input type="button" name="" id="btn3" value="Uniform speed to 100 px">
          <input type="button" name="" id="btn4" value="Constant speed to 400 px">
        </div>
        </div>
      </body>
    </html>
    

Stop condition of motion

  • Motion termination condition
    • Uniform motion: two points close enough (change position directly), math ABS () takes absolute value
    • Buffer movement: two points coincide (after rounding)
  • Code: ditto

JS sports application

Multi object motion frame

  • Multiple objects moving at the same time

    • Example: multiple

      div
      

      , the mouse moves in and widens

      • Single timer, problem
      • One timer per div
  • Multi object motion frame

    • Timer as an object attribute

    • Parameter transfer: object, target value

    • Example: multiple

      div
      

      Fade in and out

      • Nothing can be shared
      • Attributes are bound to moving objects: speed, other attribute values (such as transparency, etc.)
  • Code: same as below

Arbitrary value motion frame

  • Bug of offset attribute

    • Get the size of the whole box model, and the div with border becomes wider
      • Use obj Currentstyle ('name ') and getcomputedstyle (obj,' ') Name instead of offset
  • Problem of original motion frame

    • Only one value can move
    • If you want other values to move, modify the program
  • Extended motion frame

    • Motion attributes as parameters

    • encapsulation

      opacity
      
      • Decimal precision problem: math Round() round
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <link rel="stylesheet" href="../reset.css">
        <title>Buffer movement and stop conditions</title>
        <style>
          body {
            width: 800px;
            height: 2000px;
          }
          div {
            width: 100px;
            height: 100px;
            background-color: darkblue;
          }
          #div1 {
            position: absolute;
          }
          #div2 {       
            position: absolute;
            top: 110px;
          }
          #div3 {
            position: absolute;
            top: 220px;
          }
          #div4 {
            position: absolute;
            top: 330px;
            opacity: 0.3;
            filter: alpha(opacity=30);
          }
          #div5 {
            position: absolute;
            top: 440px;
            opacity: 0.3;
            filter: alpha(opacity=30);
          }
          #div6 {
            position: absolute;
            top: 550px;
            opacity: 0.3;
            filter: alpha(opacity=30);
          }
          #div7 {
            left: 400px;
            position: absolute;
          }
          #div8 {
            left: 510px;
            position: absolute;
            border: red solid 10px;
          }
          #div9 {
            left: 110px;
            top: 330px;
            position: absolute;
            color: seashell;
          }
          #div10 {
            left: 110px;
            top: 440px;
            position: absolute;
            border: rgb(255, 106, 0) solid 1px;
          }
          #div11 {
            left: 110px;
            top: 550px;
            position: absolute;
            opacity: 0.2;
            filter: alpha(opacity=20);
          }
        </style>
        <script>
          window.onload = function () {
            // Encapsulate getElementById
            function get(id) {
              return document.getElementById(id);
            };
            // Encapsulates the function to obtain the calculated element style and return decimal
            function getStyle(obj, name) {
              if (obj.currentStyle) {
                return obj.currentStyle[name];
              } else {
                return getComputedStyle(obj, '') [name];
              }
            }
    
            //  The multi-object motion frame offset obtains the size of the whole box, which cannot be used in general
            // function startMove(obj, iTarget, name) {
            //   clearInterval(obj.timer);
            //   obj.timer = setInterval(move, 30);
            //   function move() {
            //     iTarget = parseInt(iTarget);
            //     var speed = (iTarget - obj['offset'+name])/7;  
            //     if (speed < 0) {
            //       speed = Math.floor(speed);
            //     } else {
            //       speed = Math.ceil(speed);
            //     }
            //     if (iTarget === obj['offset'+name]) {
            //       clearInterval(obj.timer);
            //     } else {
            //       obj.style[name.toLowerCase()] = obj['offset'+name] + speed + 'px'; 
            //     }
                
            //     console.log(iTarget,obj['offset'+name],speed)
            //   }
            // }
    
            // Arbitrary value motion frame
            function startMove(obj, iTarget, name) {
              clearInterval(obj.timer);
              obj.timer = setInterval(move, 30);
              function move() {
                var objName = 0;
                if (name === 'opacity') {
                  // Use parseFloat to keep the decimal and remove the following px, extract the number from left to right, and jump out if it is not a number
                  // Math.round() round 
                  objName = Math.round(parseFloat(getStyle(obj, name))*100);
                } else {
                  // Use parseInt to remove the following px and extract numbers from left to right. If it is not a number, it will jump out
                  objName = parseInt(getStyle(obj, name));
                }
                var speed = (iTarget - objName)/7;  
                if (speed < 0) {
                  speed = Math.floor(speed);
                } else {
                  speed = Math.ceil(speed);
                }
                if (iTarget === objName) {
                  clearInterval(obj.timer);
                } else {
                  if (name === 'opacity') {
                    obj.style[name] = (objName + speed)/100;
                    obj.style.filter = "alpha("+[name]+ "=" + (objName + speed) + ")"; 
                  } else {
                    obj.style[name] = objName + speed + 'px'; 
                  }
                }
                console.log('iTarget',iTarget,'objName',objName,'getStyle',getStyle(obj, name),speed)
              }
            }
    
            var oDiv1 = get('div1');
            var oDiv2 = get('div2');
            var oDiv3 = get('div3');
            var oDiv7 = get('div7');
            var oDiv8 = get('div8');
            var oDiv9 = get('div9');
            var oDiv10 = get('div10');
            var oDiv11 = get('div11');
            // Widening
            oDiv1.onmouseover = function () {
              startMove(oDiv1, 400, 'width')
            }
            oDiv1.onmouseout = function () {
              startMove(oDiv1, 100, 'width')
            }
            oDiv2.onmouseover = function () {
              startMove(oDiv2, 400, 'width')
            }
            oDiv2.onmouseout = function () {
              startMove(oDiv2, 100, 'width')
            }
            oDiv3.onmouseover = function () {
              startMove(oDiv3, 400, 'width')
            }
            oDiv3.onmouseout = function () {
              startMove(oDiv3, 100, 'width')
            }
            // Get higher
            oDiv7.onmouseover = function () {
              startMove(oDiv7, 400, 'height')
            }
            oDiv7.onmouseout = function () {
              startMove(oDiv7, 100, 'height')
            }
            oDiv8.onmouseover = function () {
              startMove(oDiv8, 400, 'height')
            }
            oDiv8.onmouseout = function () {
              startMove(oDiv8, 100, 'height')
            }
            oDiv9.onmouseover = function () {
              startMove(oDiv9, 40, 'fontSize')
            }
            oDiv9.onmouseout = function () {
              startMove(oDiv9, 12, 'fontSize')
            }
            oDiv10.onmouseover = function () {
              startMove(oDiv10, 100, 'borderWidth')
            }
            oDiv10.onmouseout = function () {
              startMove(oDiv10, 1, 'borderWidth')
            }
            oDiv11.onmouseover = function () {
              startMove(oDiv11, 100, 'opacity')
            }
            oDiv11.onmouseout = function () {
              startMove(oDiv11, 20, 'opacity')
            }
    
            // Fade in and out
            function shallowMove(obj, iTarget) {
              clearInterval(obj.timer);
              obj.timer = setInterval(move, 30);
              function move() {
                iTarget = parseInt(iTarget);
                var speed = (iTarget - obj.alpha)/7;  
                if (speed < 0) {
                  speed = Math.floor(speed);
                } else {
                  speed = Math.ceil(speed);
                }
                if (iTarget === obj.alpha) {
                  clearInterval(obj.timer);
                } else {
                  obj.alpha += speed;
                  obj.style.opacity = obj.alpha/100 ; 
                  obj.style.filter = "alpha(opacity="+ obj.alpha + ")";
                }
              }
            }
            var oDiv4 = get('div4');
            var oDiv5 = get('div5');
            var oDiv6 = get('div6');
            var aDiv = document.getElementsByTagName('div');
            for (var i in aDiv) {
              aDiv[i].alpha = 30;
            }
    
            oDiv4.onmouseover = function () {
              shallowMove(oDiv4, 100)
            }
            oDiv4.onmouseout = function () {
              shallowMove(oDiv4, 30)
            }
            oDiv5.onmouseover = function () {
              shallowMove(oDiv5, 100)
            }
            oDiv5.onmouseout = function () {
              shallowMove(oDiv5, 30)
            }
            oDiv6.onmouseover = function () {
              shallowMove(oDiv6, 100)
            }
            oDiv6.onmouseout = function () {
              shallowMove(oDiv6, 30)
            }
          }
        </script>
      </head>
      <body>
        <div id="div1"></div>
        <div id="div2"></div>
        <div id="div3"></div>
        <div id="div4"></div>
        <div id="div5"></div>
        <div id="div6"></div>
        <div id="div7"></div>
        <div id="div8"></div>
        <div id="div9">123adsfzv</div>
        <div id="div10"></div>
        <div id="div11"></div>
      </body>
    </html>
    

Imitation Flash picture display

  • Effect idea

    • Buttons on both sides: fade in and fade out
    • Large drop-down: level and height change
    • li below: multi object fade in and fade out
    • ul below: position calculation
  • Left and right buttons

    • Fade in and out
      • Move the mouse over the button and the button will disappear
        • hierarchy problem
        • Events have to be added to both buttons and masks
  • Lower li effect

    • Click to switch to the big picture: tab
    • Lifade in and fade out: move in and out
    • ul movement: position calculation
  • Large picture switching

    • Picture level: z-Index + 1
    • Picture drop-down effect (motion frame)
      • You can fade in and out instead
  • Join autoplay

    • Same as tab
  • code:

    <!DOCTYPE html>
    <html>
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
      <title>Imitation Flash Picture display</title>
      <link rel="stylesheet" href="../reset.css">
      <script src="./lib/move.js"></script>
      <style>
        body {
          width: 100%;
          height: 100%;
          background-color: cornsilk;
        }
        li {
          float: left;
        }
        /* Center div */
        #div_center {
          margin: 20px auto;
          width: 640px;
          height: 450px;
        }
        /* Positioning div */
        #div_position {
          width: 640px;
          height: 450px;
          overflow: hidden;
          background-color: rgb(70, 70, 70);
          position: absolute;
        }
    
        /* Large drawing style */
        #div_pic {
          width: 640px;
          height: 360px;
          overflow: hidden;
          position: relative;
        }
        .ul_pic {
          position: absolute;
        }
        .li_pic {
          position: absolute;
        }
        .li_pic img{
          width: 640px;
          height: 360px;
        }
    
        /* Left and right key style */
        .ul_btn {
          top: 0px;
          width: 640px;
          height: 360px;
          position: absolute;
          float: left;
        }
        .slider_btn_left, .slider_btn_right {
          width: 150px;
          height: 360px;
        }
        .slider_btn_right {
          float: right;
        }
        .slider_btn_left img{
          padding: 150px 105px 150px 10px ;
          position: relative;
          width: 35px;
          height: 60px;
          opacity: 0;
          filter: alpha(opacity=0);
          float: left;
        }
        .slider_btn_right img{
          padding: 150px 10px 150px 105px ;
          position: relative;
          width: 35px;
          height: 60px;
          opacity: 0;
          filter: alpha(opacity=0);
          float: right;
        }
    
        /* Thumbnail style */
        #div_thumbnail {
          width: 620px;
          background-color: rgb(70, 70, 70);
          margin: 0 10px 0 5px;
          overflow: hidden;
          position: relative;
        }
        .ul_thumbnail {
          width: 640px;
          height: 90px;
        }
        .li_thumnali {
          opacity: 0.5;
          filter: alpha(opacity=50);
        }
        .li_thumnali img{
          padding: 10px 0px 10px 10px;
          width: 125px;
          height: 70px;
        }
    
        /* Picture text bar */
        .ul_txt {
          width: 640px;
          height: 20px;
          position: absolute;
          top: 340px;
        }
        .li4_background {
          width: 640px;
          height: 20px;
          top: 0px;
          background-color: rgb(0, 0, 0);
          opacity: 0.5;
          filter: alpha(opacity=50);
        }
        .li4_introduction {
          top: -17px;
          margin-left: 10px;
          width: 500px;
          position: relative;
          color: rgb(255, 255, 255);
          filter: alpha(opacity=80);
          opacity: 0.8;
        }
        .li4_sum_num {
          width: 120px;
          top: -17px;
          left: 10px;
          position: relative;
          color: rgb(255, 255, 255);
          filter: alpha(opacity=80);
          opacity: 0.8;
        }
      </style>
      <script>
      window.onload = function () {
        // Encapsulate getElementById
        function get(id) {
          return document.getElementById(id);
        }
        // Encapsulate getElementsByTagName
        function gets(tagName) {
          return document.getElementsByTagName(tagName)
        }
        // Encapsulate getByClassName method
        function getByClassName(oParent, sClass) {
          var aResult = new Array();
          var aEle = document.getElementsByTagName('*');
          for (var i in aEle) {
            if (aEle[i].className === sClass) {
              aResult.push(aEle[i]);
            }
          }
          return aResult;
        }
    
        // Left and right arrows switch pictures
        // Gets the location of the arrow
        var oDiv_position = get('div_position');
        var ul_btn = getByClassName(oDiv_position[1], 'ul_btn')[0];
        // Get li
        var li_btn_left = getByClassName(ul_btn, 'slider_btn_left')[0];
        var li_btn_right = getByClassName(ul_btn, 'slider_btn_right')[0];
        // Get img
        var left_icon = getByClassName(li_btn_left, 'left_icon')[0];
        var right_icon = getByClassName(li_btn_right, 'right_icon')[0];
        // Mouse in / out show / hide
        li_btn_left.onmouseover = left_icon.onmouseover = function () {
          startMove(left_icon, 'opacity', 30);
        }
        li_btn_left.onmouseout = left_icon.onmouseout = function () {
          startMove(left_icon, 'opacity', 0);
        }
        li_btn_right.onmouseover = right_icon.onmouseover = function () {
          startMove(right_icon, 'opacity', 30);
        }
        li_btn_right.onmouseout = right_icon.onmouseout = function () {
          startMove(right_icon, 'opacity', 0);
        }
    
        // Get large class li
        var ul_pic = getByClassName(oDiv_position[1], 'ul_pic')[0];
        var oli_pic = getByClassName(ul_pic, 'li_pic');
        var oImg = gets('img');
    
        // Get thumbnail class li
        var div_thumbnail = get('div_thumbnail');
        var ul_thumbnail = getByClassName(div_thumbnail, 'ul_thumbnail')[0];
        var oli_thumnali = getByClassName(ul_thumbnail, 'li_thumnali');
        var pic_index = 0;
        var index = 0;
        var z = 1;
        // Move the thumbnail mouse into the highlight, move out of the recovery, and register the index binding large image
        for (var i in oli_thumnali) {
          oli_thumnali[i].index = i;
          oli_pic[i].index = i;
          // Mouse in
          oli_thumnali[i].onmouseover = function () {
            startMove(this, 'opacity', 100);
          }
          // If the mouse is currently displayed, it will not be executed
          oli_thumnali[i].onmouseout= function () {
            if (oli_pic[this.index].style.zIndex != z) {
              startMove(this, 'opacity', 50);
            }
          }
          // Click the small picture to display the large picture
          oli_thumnali[i].onclick = function () {
            console.log(pic_index,parseInt(this.index))
            // If you click this index > 2 && this. index - pic_ Index > 0 moves to the right
            if (parseInt(this.index) > 2 && this.index - pic_index >0) {
              pic_index = parseInt(this.index);
              // The next one will be + + first--
              pic_index--;
              right_icon.onclick();
            } // If this index > 2 && this. index - pic_ Move left if index < 0
            else if (this.index > 0 && this.index - pic_index < 0) {
              pic_index = parseInt(this.index);
              // Next one -- first++
              pic_index++;
              left_icon.onclick();
            } else {
              pic_index = parseInt(this.index);
              tab();
            }
          }
          // Let the first picture show
          if (oli_pic[i].style.zIndex == z) {
            startMove(oli_thumnali[i], 'opacity', 100);
          }
        }
        // Click the mouse button previous / next
        left_icon.onclick = function () {
          // Is < 0
          if (0 <= pic_index - 1) {
            // console.log('1~length-1:',pic_index)
            pic_index--;
            if (0 < pic_index && pic_index <= oli_thumnali.length - 1) {
              // 1~length-1
              startMove(ul_thumbnail, 'marginLeft', -(pic_index-1)*li_thumbnali_width);
              tab(); 
            } else {
              // 0 
              tab();
            }
          } else {
            // < 0 reset pic_index looping
            // console.log('0:',pic_index)
            pic_index = oli_thumnali.length - 1;
            startMove(ul_thumbnail, 'marginLeft', -(pic_index-2)*li_thumbnali_width);
            tab();
          }
        }
        right_icon.onclick = function () {
          // Judge whether the next sheet is greater than the total
          if (pic_index + 1 < oli_thumnali.length) {
            pic_index++;
            // console.log('1~oli_thumnali.length-1: ',pic_index);
            if (2 < pic_index && pic_index <= oli_thumnali.length - 1) {
              startMove(ul_thumbnail, 'marginLeft', -(pic_index-2)*li_thumbnali_width);
              tab(); 
            } else {
              tab();
            }
          } else {
            // Greater than oli_thumnali.length-1 jumps to the first page
            pic_index = 0;
            startMove(ul_thumbnail, 'marginLeft', pic_index*li_thumbnali_width);
            tab();
          }
        }
        
        function tab() {
          // Determine whether it is the currently displayed picture
          if (oli_pic[pic_index].style.zIndex != z) {
            // All pictures are translucent
            for (var j in oli_thumnali) {
              startMove(oli_thumnali[j], 'opacity', 50);
            }
            // Display the currently clicked picture
            startMove(oli_thumnali[pic_index], 'opacity', 100);
            // Display the corresponding large picture of the current index
            oli_pic[pic_index].style.zIndex = ++z;
            // Button to display text
            ul_btn.style.zIndex = ul_txt.style.zIndex = z;
            // Hide the large picture and then display it with animation
            oImg[pic_index].style.height = 0;
            startMove(oImg[pic_index],'height', 360);
            // Show current picture introduction
            introduction.innerHTML = arr[pic_index];
            sum_num.innerHTML = parseInt(pic_index) + 1 + '/' + oli_thumnali.length;
          }
        }
    
        // Auto play
        oDiv_position.timer = setInterval(right_icon.onclick, 2000);
        oDiv_position.onmouseover = function () {
          clearInterval(oDiv_position.timer);
        }
        oDiv_position.onmouseout = function () {
          clearInterval(oDiv_position.timer);
          oDiv_position.timer = setInterval(right_icon.onclick, 2000);
        }
        // Set UL_ Width of thumbnail
        var li_thumbnali_width = oli_thumnali[0].offsetWidth;
        ul_thumbnail.style.width = oli_thumnali.length * oli_thumnali[0].offsetWidth + 'px';
    
        // Set text description
        var arr = new Array('Snow Mountain','canyon','Steep cliff','Rock wall','coast','Snow covered cliff','Snow Mountain','canyon','Steep cliff','Rock wall','coast','Snow covered cliff');
        // Get text description li
        var ul_txt = getByClassName(oDiv_position[1], 'ul_txt')[0];
        var introduction = getByClassName(ul_txt, 'introduction')[0];
        var sum_num = getByClassName(ul_txt, 'sum_num')[0];
        sum_num.innerHTML = pic_index + 1 + '/' + oli_thumnali.length;
        introduction.innerHTML = arr[pic_index];
      }
      </script>
      <body>
        <div id="div_center">
          <div id="div_position">
            <div id="div_pic">
              <ul class="ul_pic">
                <li class="li_pic" style="z-index:1"><img src="./images/album/1.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/3.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/4.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/5.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/6.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/5.jpeg" alt=""></li>
              </ul>
            </div>
            <ul class="ul_btn" style="z-index:1">
              <li class="slider_btn_left"><img class="left_icon" src="./images/images/slider_btn_icon_left.png" alt=""></li>
              <li class="slider_btn_right"><img class="right_icon" src="./images/images/slider_btn_icon_right.png" alt=""></li>
            </ul>
            <ul class="ul_txt" style="z-index:1">
              <li class="li4_background"></li>
              <li class="li4_introduction">Picture Description:<span class="introduction">introduction</span></li>
              <li class="li4_sum_num">Picture location:<span class="sum_num"></span></li>
            </ul>
            <div id="div_thumbnail">
              <ul class="ul_thumbnail">
                <li class="li_thumnali"><img src="./images/album/1.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/3.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/4.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/5.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/6.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/5.jpeg" alt=""></li>
              </ul>
            </div>
          </div>
        </div>
      </body>
    </html>
    
  • // ./lib/move.js
    // Encapsulates the function to obtain the calculated element style and return decimal
    function getStyle(obj, name) {
      if (obj.currentStyle) {
        return obj.currentStyle[name];
      } else {
        return getComputedStyle(obj, '') [name];
      }
    }
            // Arbitrary value motion frame
    function startMove(obj, name, iTarget ) {
      clearInterval(obj.timer);
      obj.timer = setInterval(move, 30);
      function move() {
        var current = 0;
        if (name === 'opacity') {
          // Use parseFloat to keep the decimal and remove the following px, extract the number from left to right, and jump out if it is not a number
          // Math.round() round 
          current = Math.round(parseFloat(getStyle(obj, name))*100);
        } else {
          // Use parseInt to remove the following px and extract numbers from left to right. If it is not a number, it will jump out
          current = parseInt(getStyle(obj, name));
        }
        var speed = (iTarget - current)/3;  
        if (speed < 0) {
          speed = Math.floor(speed);
        } else {
          speed = Math.ceil(speed);
        }
        if (iTarget === current) {
          clearInterval(obj.timer);
        } else {
          if (name === 'opacity') {
            obj.style[name] = (current + speed)/100;
            obj.style.filter = "alpha("+[name]+ "=" + (current + speed) + ")"; 
          } else {
            obj.style[name] = current + speed + 'px'; 
          }
        }
        // console.log('iTarget',iTarget,'current',current,'getStyle',getStyle(obj, name),speed)
      }
    }
    
  • Note: do not let child elements inherit the parent element's opacity attribute

    • Use rgba(R,G,B,opacity) to indirectly set the value of opacity. This attribute will not inherit downward
    • Or put the opacity attribute into the implementation of the peer element
  • Note: only when the parent uses relative positioning can the child be absolutely positioned within the range

JS sports intermediate

Chain motion frame

  • Callback function:

    startMove(obj, attr, iTarget, fn)
    
    • When the motion stops, the function is executed
    • When the movement stops, start the next movement
    • Example: the menu in the lower right corner of tudou.com

Perfect motion frame

  • Multiple values change simultaneously: startMove(obj, json)

    • setStyle
      

      Set multiple properties at the same time

      • Parameter transfer:
        • Use of JSON
        • for in traversal property
  • Apply to motion frame

  • Detect movement stop

    • Flag variable
  • Example: a menu that zooms in and out at the same time

  • code:

    // ./lib/move2.js
    // Encapsulates the function to obtain the calculated element style and return decimal
    function getStyle(obj, name) {
      if (obj.currentStyle) {
        return obj.currentStyle[name];
      } else {
        return getComputedStyle(obj, '') [name];
      }
    }
            // Arbitrary value motion frame
    function startMove(obj, json, fnEnd ) {
      clearInterval(obj.timer);
      obj.timer = setInterval(move, 30);
      function move() {
        var current = 0;
        var stop = true;
        for (const attr in json) {
          if (attr === 'opacity') {
            // Use parseFloat to keep the decimal and remove the following px, extract the number from left to right, and jump out if it is not a number
            // Math.round() round 
            current = Math.round(parseFloat(getStyle(obj, attr))*100);
          } else {
            // Use parseInt to remove the following px and extract numbers from left to right. If it is not a number, it will jump out
            current = parseInt(getStyle(obj, attr));
          }
          var speed = (json[attr] - current)/4;  
          if (speed < 0) {
            speed = Math.floor(speed);
          } else {
            speed = Math.ceil(speed);
          }
          if (json[attr] === current) {
            stop = true;
          } else {
            stop = false;
            if (attr === 'opacity') {
              obj.style[attr] = (current + speed)/100;
              obj.style.filter = "alpha("+[attr]+ "=" + (current + speed) + ")"; 
            } else {
              obj.style[attr] = current + speed + 'px'; 
            }
          }
          console.log('json[attr]:',json[attr],'attr:', attr,'current:',current,'getStyle:',getStyle(obj, attr),'speed:',speed);
        }
        if (stop === true) {
          clearInterval(obj.timer);
          if (fnEnd) {
            fnEnd()
          }
        }
      }
    }
    
  • <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Chain motion frame</title>
        <style>
          body {
            width: auto;
            height: 2000px;
          }
          #div1 {
            width: 50px;
            height: 50px;
            background: rgb(99, 128, 255);
            position: absolute;
          }
          #div_p {
            width: 50px;
            height: 50px;
            background-color: cornsilk;
            position: absolute;
            right: 0;
            top: 50%;
          }
          #div2 {
            width: 50px;
            height: 50px;
            background: rgb(99, 128, 255);
            position: absolute;
          }
          #div3 {
            position: absolute;
            height: 50px;
            width: 0px;
            right: 50px;
            background-color: rgb(119, 95, 255);
            overflow: hidden;
          }
          #div4 {
            position: absolute;
            width: 100px;
            height: 0px;
            right: 50px;
            top: 0px;
            overflow: hidden;
            background-color: rgb(98, 163, 248);
          }
          #close {
            position: absolute;
            float: right;
            right: 5px;
            color: white;
          }
        </style>
        <script src="./lib/move2.js"></script>
        <script>
        window.onload = function () {
          // Encapsulate getElementById
          function get(id) {
            return document.getElementById(id);
          }
    
          var btn1 = get('btn1');
          var div1 = get('div1');
          btn1.onclick = function () {
            startMove(div1,{'height': 400, "width": 101, "opacity": 30, "left": 100, "top": 200}, msg);
          }
          function msg() {
            console.log('Chain function execution completed!')
          }
    
          // Buffer sidebar that follows page scrolling
          var div_p = get('div_p');
          window.onscroll = function () {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            var odiv_pHeight = parseInt(getStyle(div_p, 'height'));
            var target = parseInt((document.documentElement.clientHeight - odiv_pHeight)/2 + scrollTop);
            startMove(div_p, {"top":target});
            console.log(
              'Viewing area:', document.documentElement.clientHeight,
              'Rolling distance:', scrollTop, 
              'div3 Height of:', getStyle(div_p, 'height'), 
              'Target value:', target) 
          }
    
          // Potato telescopic menu bar
          var div2 = get('div2'); 
          var div3 = get('div3');
          var div4 = get('div4');
          var close = get('close');
          div2.onclick = function () {
            // div3.style.display = 'block';
            // div4.style.display = 'block';
            startMove(div3, {"width":100},fnEnd)
            function fnEnd() {
              startMove(div4,{"height":100, "top":-100})
            }
          }
          close.onclick = function () {
            startMove(div4, {"top": 0, "height": 0}, fnEnd);
            function fnEnd() {
            startMove(div3, {"width":0})
            }
          }
        }
        </script>
      </head>
      <body>
        <input type="button" id="btn1" value="Chain motion">
        <div id="div1"></div>
        <div id="div_p">
          <div id="div2">potato</div>
          <div id="div3">player</div>
          <div id="div4"><a id="close" href="javascript:;">close</a></div>
        </div>
      </body>
    </html>
    

Motion frame summary

  • Evolution process of motion frame
    • startMove(iTarget): motion frame
    • startMove(obj, iTarget): multiple objects
    • startMove(obj, attr, iTarget): any value
    • startMove(obj, attr, iTarget, fn): chain motion
    • startMove(obj, json): multivalued motion
    • startMove(obj, json, fn): perfect motion frame

Motion frame application

  • Motion frame application

    • Example: slides
  • Example: Sina Weibo

    • Chain motion

    • Note: the CSS white space property preserves line breaks

      value			describe
      normal		Default. Whitespace is ignored by the browser.
      pre			Blank will be retained by the browser. It behaves in a similar way HTML Medium <pre> label.
      nowrap		The text does not wrap, and the text continues on the same line until it is encountered <br> Until the label.
      pre-wrap	The whitespace sequence is retained, but line breaks are performed normally.
      pre-line	Merges whitespace sequences, but preserves line breaks.
      inherit		Specifies that it should inherit from the parent element white-space The value of the property.
      
  • code:

    <!DOCTYPE html>
    <html>
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
      <title>Slide up and down and Sina Weibo effect</title>
      <link rel="stylesheet" href="../reset.css">
      <link rel="stylesheet" href="./css/18.1.css">
      <script src="./lib/move2.js"></script>
      <script>
      window.onload = function () {
        // Encapsulate getElementById
        function get(id) {
          return document.getElementById(id);
        }
        // Encapsulate getElementsByTagName
        function gets(tagName) {
          return document.getElementsByTagName(tagName)
        }
        // Encapsulate getByClassName method
        function getByClassName(oParent, sClass) {
          var aResult = new Array();
          var aEle = document.getElementsByTagName('*');
          for (var i in aEle) {
            if (aEle[i].className === sClass) {
              aResult.push(aEle[i]);
            }
          }
          return aResult;
        }
    
        // Left and right arrows switch pictures
        // Gets the location of the arrow
        var oDiv_position = get('div_position');
        var ul_btn = getByClassName(oDiv_position[1], 'ul_btn')[0];
        // Get li
        var li_btn_left = getByClassName(ul_btn, 'slider_btn_left')[0];
        var li_btn_right = getByClassName(ul_btn, 'slider_btn_right')[0];
        // Get img
        var left_icon = getByClassName(li_btn_left, 'left_icon')[0];
        var right_icon = getByClassName(li_btn_right, 'right_icon')[0];
        // Mouse in / out show / hide
        li_btn_left.onmouseover = left_icon.onmouseover = function () {
          startMove(left_icon, {'opacity': 30});
        }
        li_btn_left.onmouseout = left_icon.onmouseout = function () {
          startMove(left_icon, {'opacity': 0});
        }
        li_btn_right.onmouseover = right_icon.onmouseover = function () {
          startMove(right_icon, {'opacity': 30});
        }
        li_btn_right.onmouseout = right_icon.onmouseout = function () {
          startMove(right_icon, {'opacity': 0});
        }
    
        // Get large class li
        var ul_pic = getByClassName(oDiv_position[1], 'ul_pic')[0];
        var oli_pic = getByClassName(ul_pic, 'li_pic');
        var oImg = gets('img');
    
        // Get thumbnail class li
        var div_thumbnail = get('div_thumbnail');
        var ul_thumbnail = getByClassName(div_thumbnail, 'ul_thumbnail')[0];
        var oli_thumnali = getByClassName(ul_thumbnail, 'li_thumnali');
        var pic_index = 0;
        var index = 0;
        var z = 1;
        // Move the thumbnail mouse into the highlight, move out of the recovery, and register the index binding large image
        for (var i in oli_thumnali) {
          oli_thumnali[i].index = i;
          oli_pic[i].index = i;
          // Mouse in
          oli_thumnali[i].onmouseover = function () {
            startMove(this, {'opacity': 100});
          }
          // If the mouse is currently displayed, it will not be executed
          oli_thumnali[i].onmouseout= function () {
            if (oli_pic[this.index].style.zIndex != z) {
              startMove(this, {'opacity': 50});
            }
          }
          // Click the small picture to display the large picture
          oli_thumnali[i].onclick = function () {
            console.log(pic_index,parseInt(this.index))
            // If you click this index > 2 && this. index - pic_ Index > 0 moves to the right
            if (parseInt(this.index) > 2 && this.index - pic_index >0) {
              pic_index = parseInt(this.index);
              // The next one will be + + first--
              pic_index--;
              right_icon.onclick();
            } // If this index > 0 && this. index - pic_ Move left if index < 0
            else if (this.index > 0 && this.index - pic_index < 0) {
              pic_index = parseInt(this.index);
              // Next one -- first++
              pic_index++;
              left_icon.onclick();
            } else {
              pic_index = parseInt(this.index);
              tab();
            }
          }
          // Let the first picture show
          if (oli_pic[i].style.zIndex == z) {
            startMove(oli_thumnali[i], {'opacity': 100});
          }
        }
        // Click the mouse button previous / next
        var slide = ''; // Sliding direction
        left_icon.onclick = function () {
          // Is < 0
          if (0 <= pic_index - 1) {
            // console.log('1~length-1:',pic_index)
            pic_index--;
            if (0 < pic_index && pic_index <= oli_thumnali.length - 1) {
              // 1~length-1
              startMove(ul_thumbnail, {'marginLeft': -(pic_index-1)*li_thumbnali_width});
              // Slide right effect
              slide = 'right';
              tab(); 
            } else {
              // 0 
              slide = 'right';
              tab();
            }
          } else {
            // < 0 reset pic_index looping
            // console.log('0:',pic_index)
            pic_index = oli_thumnali.length - 1;
            startMove(ul_thumbnail, {'marginLeft': -(pic_index-2)*li_thumbnali_width});
            tab();
          }
        }
        right_icon.onclick = function () {
          // Judge whether the next sheet is greater than the total
          if (pic_index + 1 < oli_thumnali.length) {
            pic_index++;
            // console.log('1~oli_thumnali.length-1: ',pic_index);
            if (2 < pic_index && pic_index <= oli_thumnali.length - 1) {
              startMove(ul_thumbnail, {'marginLeft': -(pic_index-2)*li_thumbnali_width});
              // Slide left effect
              slide = 'left';
              tab(); 
            } else {
              slide = 'left';
              tab();
            }
          } else {
            // Greater than oli_thumnali.length-1 jumps to the first page
            pic_index = 0;
            startMove(ul_thumbnail, {'marginLeft': pic_index*li_thumbnali_width});
            tab();
          }
        }
        
        function tab() {
          // Determine whether it is the currently displayed picture
          if (oli_pic[pic_index].style.zIndex != z) {
            // All pictures are translucent
            for (var j in oli_thumnali) {
              startMove(oli_thumnali[j], {'opacity': 50});
            }
            // Display the currently clicked picture
            startMove(oli_thumnali[pic_index], {'opacity': 100});
            // Display the corresponding large picture of the current index
            oli_pic[pic_index].style.zIndex = ++z;
            // Button to display text
            ul_btn.style.zIndex = ul_txt.style.zIndex = z;
            // Hide the large picture and then display it with animation
            // oImg[pic_index].style.height = 0;
            // oli_pic[pic_index].style.top = '-360px';
            // oImg[pic_index].style.width = '0px';
            // startMove(oImg[pic_index],{"width": 640, "height": 360});
            if (slide === 'left') {
              oli_pic[pic_index].style.left = '640px';
              startMove(oli_pic[pic_index],{"left": 0});
              // Judge whether there is a next two splices
              if (pic_index-1 > 0 && pic_index+1 < oli_pic.length)
              startMove(oli_pic[pic_index-1],{"left": -640});
            } else if (slide === 'right') {
              oli_pic[pic_index].style.left = '-640px';
              startMove(oli_pic[pic_index],{"left": 0});
              // Judge whether there is a next two splices
              if (pic_index+1 < oli_pic.length) {
                startMove(oli_pic[pic_index+1],{"left": 640});
              }
            } else {
              oImg[pic_index].style.height = '0px';
              startMove(oImg[pic_index],{"height": 360});
            }
    
            // Show current picture introduction
            introduction.innerHTML = arr[pic_index];
            sum_num.innerHTML = parseInt(pic_index) + 1 + '/' + oli_thumnali.length;
          }
        }
    
        // Auto play
        oDiv_position.timer = setInterval(right_icon.onclick, 2000);
        oDiv_position.onmouseover = function () {
          clearInterval(oDiv_position.timer);
        }
        oDiv_position.onmouseout = function () {
          clearInterval(oDiv_position.timer);
          oDiv_position.timer = setInterval(right_icon.onclick, 2000);
        }
        // Set UL_ Width of thumbnail
        var li_thumbnali_width = oli_thumnali[0].offsetWidth;
        ul_thumbnail.style.width = oli_thumnali.length * oli_thumnali[0].offsetWidth + 'px';
    
        // Set text description
        var arr = new Array('Snow Mountain','canyon','Steep cliff','Rock wall','coast','Snow covered cliff','Snow Mountain','canyon','Steep cliff','Rock wall','coast','Snow covered cliff');
        // Get text description li
        var ul_txt = getByClassName(oDiv_position[1], 'ul_txt')[0];
        var introduction = getByClassName(ul_txt, 'introduction')[0];
        var sum_num = getByClassName(ul_txt, 'sum_num')[0];
        sum_num.innerHTML = pic_index + 1 + '/' + oli_thumnali.length;
        introduction.innerHTML = arr[pic_index];
    
        // Sina Weibo new Weibo effect review area
        var div_com_show = get('div_com_show');
        var text_comment = get('text_comment');
        var btn_comment = get('btn_comment');
        btn_comment.onclick = function () {
          // 1. Create child nodes 2 Add text to child node 3 Set style 
          // 4. Render child nodes 5 Set transparency and get height 6 Chain animation
          var oLi = document.createElement('li');
          oLi.innerHTML = text_comment.value;
          oLi.className = 'li_comment'; 
          text_comment.value = '';
          if (div_com_show.children.length > 0) {
            div_com_show.insertBefore(oLi, div_com_show.children[0]);
          } else {
            div_com_show.appendChild(oLi);
          }
          // var iHeight = parseInt(oLi.offsetHeight) - 20; //  Forget it, padding
          var iHeight = parseInt(getStyle(oLi, 'height'));
          div_com_show.children[0].style.height = '0';
          startMove(oLi,{"height": iHeight}, function fn() {
            startMove(oLi,{"opacity":100});
          })
          
        }
      }
      </script>
      <body>
        <div id="div_center">
          <div id="div_position">
            <div id="div_pic">
              <ul class="ul_pic">
                <li class="li_pic" style="z-index:1"><img src="./images/album/1.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/3.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/4.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/5.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/6.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_pic"><img src="./images/album/5.jpeg" alt=""></li>
              </ul>
            </div>
            <ul class="ul_btn" style="z-index:1">
              <li class="slider_btn_left"><img class="left_icon" src="./images/images/slider_btn_icon_left.png" alt=""></li>
              <li class="slider_btn_right"><img class="right_icon" src="./images/images/slider_btn_icon_right.png" alt=""></li>
            </ul>
            <ul class="ul_txt" style="z-index:1">
              <li class="li4_background"></li>
              <li class="li4_introduction">Picture Description:<span class="introduction">introduction</span></li>
              <li class="li4_sum_num">Picture location:<span class="sum_num"></span></li>
            </ul>
            <div id="div_thumbnail">
              <ul class="ul_thumbnail">
                <li class="li_thumnali"><img src="./images/album/1.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/3.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/4.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/5.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/6.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/2.jpeg" alt=""></li>
                <li class="li_thumnali"><img src="./images/album/5.jpeg" alt=""></li>
              </ul>
            </div>
            <div id="div_comments">
              <div id="div_com_inp">
                <textarea class="text" name="" id="text_comment" cols="60" rows="5"></textarea>
                <input class="btn" type="button" name="" id="btn_comment" value="Comment">
              </div>
              <div id="div_com_show">
              </div>
            </div>
          </div>
        </div>
      </body>
    </html>
    
  • /* 18.1.css */
      body {
          width: 100%;
          height: 100%;
          background-color: cornsilk;
      }
      li {
          float: left;
      }
      /* Center div */
      #div_center {
          margin: 20px auto;
          width: 640px;
          height: 450px;
      }
      /* Positioning div */
      #div_position {
          width: 640px;
          height: 1100px;
          overflow: hidden;
          background-color: rgb(70, 70, 70);
          position: absolute;
      }
      
      /* Large drawing style */
      #div_pic {
          width: 640px;
          height: 360px;
          overflow: hidden;
          position: absolute;
      }
      .ul_pic {
          position: absolute;
      }
      .li_pic {
          position: absolute;
      }
      .li_pic img{
          width: 640px;
          height: 360px;
      }
      
      /* Left and right key style */
      .ul_btn {
          top: 0px;
          width: 640px;
          height: 360px;
          position: absolute;
          float: left;
      }
      .slider_btn_left, .slider_btn_right {
          width: 150px;
          height: 360px;
      }
      .slider_btn_right {
          float: right;
      }
      .slider_btn_left img{
          padding: 150px 105px 150px 10px ;
          position: relative;
          width: 35px;
          height: 60px;
          opacity: 0;
          filter: alpha(opacity=0);
          float: left;
      }
      .slider_btn_right img{
          padding: 150px 10px 150px 105px ;
          position: relative;
          width: 35px;
          height: 60px;
          opacity: 0;
          filter: alpha(opacity=0);
          float: right;
      }
      
      /* Thumbnail style */
      #div_thumbnail {
          top: 360px;
          width: 620px;
          background-color: rgb(70, 70, 70);
          margin: 0 10px 0 5px;
          overflow: hidden;
          position: absolute;
      }
      .ul_thumbnail {
          width: 640px;
          height: 90px;
      }
      .li_thumnali {
          opacity: 0.5;
          filter: alpha(opacity=50);
      }
      .li_thumnali img{
          padding: 10px 0px 10px 10px;
          width: 125px;
          height: 70px;
      }
      
      /* Picture text bar */
      .ul_txt {
          width: 640px;
          height: 20px;
          position: absolute;
          top: 340px;
      }
      .li4_background {
          width: 640px;
          height: 20px;
          top: 0px;
          background-color: rgb(0, 0, 0);
          opacity: 0.5;
          filter: alpha(opacity=50);
      }
      .li4_introduction {
          top: -17px;
          margin-left: 10px;
          width: 500px;
          position: relative;
          color: rgb(255, 255, 255);
          filter: alpha(opacity=80);
          opacity: 0.8;
      }
      .li4_sum_num {
          width: 120px;
          top: -17px;
          left: 10px;
          position: relative;
          color: rgb(255, 255, 255);
          filter: alpha(opacity=80);
          opacity: 0.8;
      }
      
      /* Comment area */
      #div_comments {
          position: absolute;
          display: block;
          top: 450px;
          padding-top: 20px;
          width: 640px;
          background-color: rgb(252, 229, 200);
      }
      #div_com_inp  {
          margin-top: 5px;
          border-top: burlywood dashed 1px;
          border-bottom: burlywood dashed 1px;
      }
      .text {
          margin: 20px 0 20px 53px;
      }
      .btn {
          margin: 20px 0 20px 20px;
          width: 70px;
          height: 70px;
      }
      #div_com_show {
          height: 475px;
          margin: 20px 50px;
          padding: 0px 20px;
          background-color: rgb(255, 255, 255);
          overflow: hidden;
      }
      .li_comment {
          white-space: pre-wrap;
          padding: 10px 5px;
          float: none;
          border-bottom: cadetblue dashed 1px;
          opacity: 0;
          filter: alpha(opacity=0);
          overflow: hidden;
      }
    

JS event Foundation

Event object and event bubble

  • What is an Event object

    • It is used to obtain the information of mouse / keyboard events: mouse position and keyboard keys

    • Example: get mouse position: clientX

    • document
      

      The essence of is the entire web page:

      document.childNodes[0].tagName = '<!DOCTYPE>'
      
      • body does not add events, because without content, there is no height
  • Get Event object * * (compatibility writing method)**

    • var oEvent = ev||event; EV for Firefox / event for IE
    • The event function passes the event object as a parameter: BTN onclick = function(ev) { var oEvent = ev||event;}
  • Event flow

    • Event flow bubbling: events are passed to the parent
      • Defoaming: oevent cancelBubble = true
      • Example: imitation select control
      • DOM event flow
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Keyboard events and emulations select Drop down box</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
          #div1 {
            width: 200px;
            height: 200px;
            position: absolute;
            background-color: rgb(255, 0, 0);
            display: none;
          }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
            return document.getElementById(id);
          }
        
        window.onload = function () {
          var oDiv = get('div1');
          var btn = get('btn');
          btn.onclick = function (ev) {
            var oEvent = ev||event;
            oDiv.style.display = 'block';
            console.log(this);
            oEvent.cancelBubble = true;
          }
          document.onclick = function () {
            oDiv.style.display = 'none';
            console.log(this);
          }
        }
        </script>
      </head>
      <body>
        <input type="button" value="display" id="btn">
        <div id="div1"></di'v>
      </body>
    </html>
    

Mouse event

  • Mouse position

    • Viewable area location: clientX, clientY

    • Example: Div following the mouse

      • Eliminate the influence of the scroll bar: the distance between the visual area and the top of the page
    • code:

      // Encapsulates the current mouse coordinate function
      function getPos(ev) {
          var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
          var scrollLeft = document.documentElement.scollLeft||document.body.scrollLeft;
      
          return {x: ev.clientX+scrollLeft, y: ev.clientY+scrollTop};
      }
      
    • Wheel event: onmousewheel wheel data: event wheelDelta

      • Code: mouse wheel controls div movement

        <!DOCTYPE html>
        <html>
          <head>
            <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
            <title>Event binding and mouse wheel</title>
            <link rel="stylesheet" href="../reset.css">
            <style>
              #div1 {
                width: 200px;
                height: 200px;
                position: absolute;
                background-color: rgb(255, 0, 0);
              }
            </style>
            <script type="text/javascript">  
              var iDis = 0;
              var scrollFunc = function (e) {  
                var oDiv1 = document.getElementById('div1');
                e = e || window.event;  
                if (e.wheelDelta) {  //Judge browser IE, Google pulley events               
                  if (e.wheelDelta > 0) { //When the pulley rolls up  
                    iDis += -e.wheelDelta;
                    oDiv1.style.top = iDis/12 + 'px';
                    console.log("The pulley rolls upward",e.wheelDelta, iDis, oDiv1.offsetTop);
                  }  
                  if (e.wheelDelta < 0) { //When the pulley rolls down   
                    iDis += -e.wheelDelta; 
                    oDiv1.style.top = iDis/12 + 'px';
                    console.log("The pulley rolls upward",e.wheelDelta, iDis, oDiv1.offsetTop);
                  }  
                } else if (e.detail) {  //Firefox events  
                  if (e.detail> 0) { //When the pulley rolls up  
                      console.log("The pulley rolls upward",e.wheelDelta);  
                  }  
                  if (e.detail< 0) { //When the pulley rolls down  
                      console.log("The pulley rolls down",e.wheelDelta);  
                  }  
                }  
              }  
              //Bind a scroll event to a page  
              if (document.addEventListener) {//firefox  
                  document.addEventListener('DOMMouseScroll', scrollFunc, false);  
              }  
              //scrollFunc method triggered by rolling pulley / / ie Google  
              window.onmousewheel = document.onmousewheel = scrollFunc;   
            </script>
          </head>
          <body>
            <div id="div1"></div>
          </body>
        </html>
        
  • Gets the absolute position of the mouse on the page

    • Encapsulation function

    • Example: a string of Div following the mouse

    • code:

      <!DOCTYPE html>
      <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
          <title>A string that follows the mouse div</title>
          <link rel="stylesheet" href="../reset.css">
          <style>
            div {
              width: 10px;
              height: 10px;
              position: absolute;
              background-color: rgb(255, 0, 0);
            }
          </style>
          <script>
          window.onload = function () {
            // Encapsulates the current mouse coordinate function
            function getPos(ev) {
              var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
              var scrollLeft = document.documentElement.scollLeft||document.body.scrollLeft;
      
              return {x: ev.clientX+scrollLeft, y: ev.clientY+scrollTop};
            }
            var oDiv = document.getElementsByTagName('div');
            document.onmousemove = function () {
              var ev = ev || event;
              // The latter element follows the previous element
              for ( var i = oDiv.length-1; i > 0; i--) {
                console.log(oDiv[i].style.left,oDiv[i-1].offsetLeft)
                oDiv[i].style.left = oDiv[i-1].offsetLeft + 'px';
                oDiv[i].style.top = oDiv[i-1].offsetTop + 'px';
              }
              // The current variable is assigned to the first element,
              var pos = getPos(ev);
              oDiv[0].style.left = pos.x + 'px';
              oDiv[0].style.top = pos.y + 'px';
            }
          }
          </script>
        </head>
        <body>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
          <div></div><div></div><div></div><div></div><div></div>
        </body>
      </html>
      

Keyboard events

  • keyCode

    • Gets which key the user pressed on the keyboard: onkeydown / onkeyup
    • Example: keyboard controls Div movement
  • Other properties

    • ctrlKey,shiftKey,altKey
    • Example: submit a message
      • Press enter to submit
      • CTRL + enter submit
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Keyboard controls element movement and carriage return submission</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
         /* Comment area */
         #div_comments {
           position: absolute;
           display: block;
           padding-top: 20px;
           width: 640px;
           background-color: rgb(252, 229, 200);
         }
         #div_com_inp  {
           margin-top: 5px;
           border-top: burlywood dashed 1px;
           border-bottom: burlywood dashed 1px;
         }
         .text {
           margin: 20px 0 20px 53px;
         }
         .btn {
           margin: 20px 0 20px 20px;
           width: 70px;
           height: 70px;
         }
         #div_com_show {
          height: 200px;
          margin: 20px 50px;
          padding: 0px 20px;
          background-color: rgb(255, 255, 255);
          overflow: hidden;
         }
         .li_comment {
           white-space: pre-wrap;
           padding: 10px 5px;
           float: none;
           border-bottom: cadetblue dashed 1px;
           opacity: 0;
           filter: alpha(opacity=0);
           overflow: hidden;
         }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
            return document.getElementById(id);
          }
        
        window.onload = function () {
          // var oDiv = get('div1');
          // document.onkeydown = function () {
          //   var ev = event||ev;
          //   if (ev.keyCode === 37) {
          //     oDiv.style.left = oDiv.offsetLeft - 10 + 'px'
          //   } else if (ev.keyCode === 39) {
          //     oDiv.style.left = oDiv.offsetLeft + 10 + 'px'
          //   } else if (ev.keyCode === 38) {
          //     oDiv.style.top = oDiv.offsetTop - 10 + 'px'
          //   } else if (ev.keyCode === 40) {
          //     oDiv.style.top = oDiv.offsetTop + 10 + 'px'
          //   }
          // }
    
          //Get Div element
          var oDiv = document.getElementById("div_comments");
     
          //Create initial variables for judging conditions in all directions
          var left = false;
          var right = false;
          var top = false;
          var bottom = false;
     
          //When the corresponding direction key is pressed, the corresponding variable is true
          document.onkeydown = function(ev){
            var oEvent = ev || event;
            var keyCode = oEvent.keyCode;
            switch(keyCode){
              case 37:
                left=true;
                break;
              case 38:
                top=true;
                break;
              case 39:
                right=true;
                break;
              case 40:
                bottom=true;
                break;
            }
          };
     
          //Set a timing for about 50, neither too high nor too low
          setInterval(function(){
     
            //When one of the conditions is true, the current function is executed (move the corresponding direction)
            if(left){
              oDiv.style.left = oDiv.offsetLeft-10+"px";
            }else if(top){
              oDiv.style.top = oDiv.offsetTop-10+"px";
            }else if(right){
              oDiv.style.left = oDiv.offsetLeft+10+"px";
            }else if(bottom){
              oDiv.style.top = oDiv.offsetTop+10+"px";
            }
          },30);
     
          //After execution, all corresponding variables return to false and remain stationary
          document.onkeyup = function(ev){
            var oEvent = ev || event;
            var keyCode = oEvent.keyCode;
     
            switch(keyCode){
              case 37:
                left=false;
                break;
              case 38:
                top=false;
                break;
              case 39:
                right=false;
                break;
              case 40:
                bottom=false;
                break;
            }
          }
    
          // btn submission
          var btn = get('btn_comment');
          var txt = get('text_comment');
          var board = get('div_com_show');
          btn.onclick = function () {
            if (true) {
              var oP = document.createElement('p');
              oP.innerHTML = txt.value;
              txt.value = '';
              if (board.children.length > 0) {
                board.insertBefore(oP,board.children[0])
              } else {
                board.appendChild(oP);
              }
            }
          }
          // ctrl + enter submit
          txt.onkeydown = function (ev) {
            var ev = ev||event;
            if (ev.keyCode === 13 && ev.ctrlKey) {
              var oP = document.createElement('p');
              oP.innerHTML = txt.value;
              txt.value = '';
              if (board.children.length > 0) {
                board.insertBefore(oP,board.children[0])
              } else {
                board.appendChild(oP);
              }
            }
          }
        }
        </script>
      </head>
      <body>
        <div id="div_comments">
          <div id="div_com_inp">
            <textarea class="text" name="" id="text_comment" cols="60" rows="5"></textarea>
            <input class="btn" type="button" name="" id="btn_comment" value="Comment">
          </div>
          <div id="div_com_show">
            <p>CTRL + Press enter to submit</p>
            <p>Keyboard control message box position</p>
          </div>
        </div>
      </body>
    </html>
    

JS event intermediate

Default event

  • Default event

    • What is the default event
  • Block default events

    • Common writing method: return false;
    • Example 1: shielding the right-click menu
      • document.oncontextmenu = function (ev) { return false; }
      • The user defined right-click menu pops up
    • Example 2: an input box that can only enter numbers
      • oTxt.onkeydown = function (ev) { return false; }
      • Difference between keydown and keyup events
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Default event</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
          #div1 {
            width: 100px;
            height: 150px;
            position: absolute;
            background-color: rgb(207, 207, 207);
            display: none;
          }
        </style>
        <script>
    
        // Block default events block context menu
        document.oncontextmenu = function (ev) {
          var ev = ev||event;
          var oDiv = get('div1');
          oDiv.style.display = 'block';
          oDiv.style.top = ev.clientY + 'px';
          oDiv.style.left = ev.clientX + 'px';
          return false;
        }
        // Click the other position to make the div disappear
        document.onclick = function (ev) {
          var oDiv = get('div1');
          oDiv.style.display = 'none';
        }
        
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
    
        window.onload = function () {
          // Text box that can only enter numbers
          // ASCII 0:48 ~ 9:58 
          var txt = get('txt');
          txt.onkeydown = function (ev) {
            var ev = ev||event;
            if (ev.keyCode <= 58 && ev.keyCode >=48 || ev.keyCode === 8) {
    
            } else {
              return false;
            }
          }
        }
        
        </script>
      </head>
      <body>
        <input type="text" name="" id="txt">
        <div id="div1">
          <li>123</li>  
          <li>456</li>  
          <li>789</li>  
          <li>123</li>  
          <li>456</li>  
          <li>789</li>  
          <li>123</li>  
          <li>456</li>  
          <li>789</li>  
        </div>
      </body>
    </html>
    

Drag

  • Simple drag and drop

    • Drag principle
      • The distance from the mouse down position to div remains unchanged
      • Three events: onmousedown onmousemove onmouseup
  • Reliable drag

    • The original drag problem: moving too fast will move the mouse out of the div
      • Add events directly to the document
    • Under FireFox, drag a Bug with an empty Div
      • Block default event: onmousedown {return false}
    • Prevent page dragging
      • Correction position: in the visual area
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Drag</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
          #div1 {
            width: 200px;
            height: 200px;
            position: absolute;
            background-color: rgb(255, 0, 0);
          }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
        window.onload = function () {
          var oDiv = get('div1');
          // oDiv.onmousedown is easy to move out of scope
          document.onmousedown = function Drag() {
            var ev = event||ev;
            var _this = this;
            // Mouse viewable area position - div left margin = mouse position within div
            var disX = ev.clientX - oDiv.offsetLeft;
            var disY = ev.clientY - oDiv.offsetTop;
            console.log(disX,'Viewable mouse X: ', ev.clientX, 'mouse Y: ',ev.clientY);
            this.onmousemove = function mouseMove() {
              // The coordinates will not be updated until the Event object is continuously obtained
              var ev = event||ev;
              // console.log('visible area mouse X: ', ev.clientX,' mouse Y: ', ev.clientY);
              // Div position = new position in the visible area of the mouse - distance between the mouse and div
              var left = ev.clientX -disX;
              var top = ev.clientY - disY;
              if (left < 0) {
                left = 0;
              }
              if (top < 0) {
                top = 0
              }
              if (left > document.documentElement.clientWidth - oDiv.offsetWidth) {
                left = document.documentElement.clientWidth - oDiv.offsetWidth + 'px';
              }
              if (top > document.documentElement.clientHeight - oDiv.offsetHeight) {
                top = document.documentElement.clientHeight - oDiv.offsetHeight + 'px';
              }
              oDiv.style.left = left + 'px';
              oDiv.style.top = top + 'px';
            }
            this.onmouseup = function mouseUp() {
              _this.onmousemove = '';
              this.onmouseup = '';
            }
            // Prevent Firefox ghosting bug
            return false;
          }
        }
        
        </script>
      </head>
      <body>
        <div id="div1"></div>
      </body>
    </html>
    

JS event advanced application

Event binding

  • IE mode:

    • Attachevent (event name, function), binding event handling function
    • Detachevent (event name, function), contact binding
  • DOM mode: incompatible with IE7

    • Addeventlistener (event name, function, capture)
    • Removeeventlistener (event name, function, capture)
  • When to use binding

  • Bind event and this

  • Bind anonymous function and cannot be deleted

  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Event binding</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
          #div1 {
            width: 200px;
            height: 200px;
            position: absolute;
            background-color: rgb(255, 0, 0);
          }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
    
        // Encapsulating attachEvent compatibility functions
        function myAddEvent(obj, ev, fn) {
          if (obj.attachEvent) {
            obj.attachEvent('on'+ ev, fn);
          } else {
            obj.addEventListener(ev, fn , false);
          }
        }
    
        window.onload = function () {
          var oDiv = get('div1');
          var btn = get('btn');
          myAddEvent(btn, 'click', function () {
            console.log('event');
            oDiv.style.display = 'none';
          })
          myAddEvent(btn, 'click', function () {
            console.log('event2');
            setTimeout(function () {
              oDiv.style.display = 'block';
            }, 1000);
          })
        }
        </script>
      </head>
      <body>
        <input type="button"  id="btn" value="Button">
        <div id="div1"></div>
      </body>
    </html>
    

Advanced drag and drop

  • Review drag and drop principle

    • Constant distance
    • Three events
  • Limit scope

    • Judge the position
      • Example 1: Div that cannot be dragged out of the window
      • Example 2: Div cannot be dragged out of the specified window
    • Magnetic adsorption
  • Picture drag

    • Block default events
  • Text selection

    • Blocking the default event return false can solve the problem of text selection in chrome, FireFox and IE9
    • There is a problem dragging under IE:
      • Event capture: setCapture() is only compatible with IE
      • Cancel capture: releaseCapture()
  • Cooperate with DOM

    • Framed drag
    • Drag in place
  • code:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Advanced drag and drop</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
          #div1 {
            width: 100px;
            height: 100px;
            position: absolute;
            background-color: rgb(82, 177, 255);
          }
          .box {
            border: black dashed 1px;
            position: absolute;
          }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
        window.onload = function () {
          var oDiv = get('div1');
          var oDiv0 = get('div0');
    
          // oDiv.onmousedown is easy to move out of scope
          oDiv.onmousedown = function Drag() {
            var ev = event||ev;
            var _this = this;
    
            // Mouse viewable area position - div left margin = mouse position within div
            var disX = ev.clientX - oDiv.offsetLeft;
            var disY = ev.clientY - oDiv.offsetTop;
            console.log(disX,'Viewable mouse X: ', ev.clientX, 'mouse Y: ',ev.clientY);
            
            // Add border
            var oBox = document.createElement('div');
            oBox.className = 'box';
            // Border size - line width = oDiv size
            oBox.style.width = this.offsetWidth - 2 + 'px';
            oBox.style.height = this.offsetHeight - 2 + 'px';
            oDiv0.appendChild(oBox);
            // Position of border = position of oDiv
            oBox.style.left = oDiv.offsetLeft + 'px';
            oBox.style.top = oDiv.offsetTop + 'px';
            // IE7 compatible
            if (this.setCapture) {
              this.onmousemove = mouseMove;
              this.onmouseup = mouseUp;
              oDiv.setCapture();
            } else {
              document.onmousemove = mouseMove;
              document.onmouseup = mouseUp;
            }
    
            function mouseUp() {
              this.onmousemove = '';
              this.onmouseup = '';
              // Release the mouse and oDiv to the position of oBox
              oDiv.style.left = oBox.offsetLeft + 'px';
              oDiv.style.top = oBox.offsetTop + 'px';
              // Delete generated box
              oDiv0.removeChild(oBox);
              // IE7 compatible
              if (this.releaseCapture) {
                this.releaseCapture();
              }
            }
    
            function mouseMove(ev) {
              // The coordinates will not be updated until the Event object is continuously obtained
              var ev = event||ev;
              // console.log('visible area mouse X: ', ev.clientX,' mouse Y: ', ev.clientY);
              // Div position = new position in the visible area of the mouse - distance between the mouse and div
              var left = ev.clientX -disX;
              var top = ev.clientY - disY;
              // Move dashed box when mouse moves
              oBox.style.left = left + 'px';
              oBox.style.top = top + 'px';
            }
            
            // Prevent the Firefox ghosting bug and solve the text selection problem of chrome FireFox IE9
            return false;
          }
        }
        
        </script>
      </head>
      <body>
        <div id="div0">
          asdfasdfas/sad'234
          <div id="div1">asdfasdfas/sad</div>
          asdfasdfas/sad'234
        </div>
      </body>
    </html>
    

Custom scroll bar

  • Drag

    • Only horizontal drag
    • Limit range: the size of the range
    • Calculation scale: current value / maximum value
  • Control other objects

    • Example 1: controlling the size of an object
    • Example 2: control the transparency of objects
    • Example 3: control text scrolling
  • code:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Custom scroll bar</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
          #div0 {
            margin: 10px auto;
            width: 600px;
            height: 400px;
            position: relative;
            background-color: blanchedalmond;
          }
          /* Scroll bar up and down */
          #div1 {
            top: 50px;
            right: 50px;
            width: 20px;
            height: 300px;
            position: absolute;
            border: rgb(139, 139, 139) solid 1px;
          }
          #div1_0 {
            width: 20px;
            height: 40px;
            position: absolute;
            background-color: rgb(140, 171, 255);
          }
          /* Text area */
          #div3 {
            left: 60px;
            top: 50px;
            width: 400px;
            height: 300px;
            position: absolute;
            background-color: rgb(255, 255, 255);
            overflow: hidden;
    
          }
          #div3_0 {
            width: 900px;
            position: absolute;
            white-space: pre-wrap;
            background-color: cornsilk;
          }
          /* Left and right scroll bars */
          #div2 {
            top: 5px;
            right: 140px;
            width: 400px;
            height: 20px;
            position: absolute;
            border: rgb(139, 139, 139) solid 1px;
          }
          #div2_0 {
            width: 40px;
            height: 20px;
            position: absolute;
            background-color: rgb(140, 171, 255);
          }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
        // Encapsulates the function to obtain the calculated element style and return decimal
        function getStyle(obj, name) {
          if (obj.currentStyle) {
            return obj.currentStyle[name];
          } else {
            return getComputedStyle(obj, '') [name];
          }
        }
    
        window.onload = function () {
    
          var oDiv1 = get('div1'); // Scroll up and down
          var oDiv1_0 = get('div1_0'); // Scroll bar up and down
          var oDiv3 = get('div3'); // Text box
          // var oDiv3_0 = get('div3_0'); //  Text viewing area
          var oDiv2 = get('div2'); // Left and right scroll boxes
          var oDiv2_0 = get('div2_0'); // Left and right scroll bars
    
          // Text TOP = (text box height - viewing area height) * (scroll bar TOP / (scroll box height - scroll bar height))
          // Event triggered when the mouse presses the scroll bar
          // When the mouse Y moves, the scroll bar top moves
          // When the mouse is released, the event ends
    
          // Merge function: EV clientY offsetTop offsetHeight oDiv1 oDiv1_ 0 oDiv3 oDiv3_ 0
          // Remove offset and use getStyle instead 
          // console.log(oDiv1.children[0], oDiv1_0) 
          // Directly pass an object to take the child node or parent node
          // Face object: srcoll as oDiv1_0 and oDiv2_0, you can use this instead of oDiv1_0, just pass in ev, 'clientY', oDiv3
          oDiv1_0.onmousedown = function (ev) {
            scroll(ev, 'clientY', oDiv1, oDiv3);
            return false; // It can solve the text selection problem of chrome FireFox IE9
          } 
          oDiv2_0.onmousedown = function (ev) {
            scroll(ev, 'clientX', oDiv2, oDiv3);
            return false; // It can solve the text selection problem of chrome FireFox IE9
          }
    
          function scroll(ev, dir, obj1 , obj2) {
            var attr = '';
            var attr2 = '';
            if (dir === 'clientY') {
              attr = 'height';
              attr2 = 'top';
            } else if (dir === 'clientX') {
              attr = 'width';
              attr2 = 'left';
            } else {
              return console.log('Parameter error');
            }
    
            var oDiv1_0 = obj1.children[0];
            var oDiv3_0 = obj2.children[0];
            var ev = ev||event;
            var disMouse = ev[dir];
            // Scroll bar old position
            var oldPos = parseInt(getStyle(oDiv1_0, attr2));
            // Scroll range = scroll bar height + scroll box Height
            var disScroll = parseInt(getStyle(obj1, attr)) - parseInt(getStyle(oDiv1_0, attr)); 
    
            document.onmousemove = function (ev) {
              ev = ev||event;
              // Moving distance
              var disMove = ev[dir] - disMouse;
              // Scroll bar TOP = scroll bar TOP + moving distance
              var divScroll = oldPos + disMove;
              // Text TOP = (text box height - viewing area height) * (scroll bar TOP / (scroll box height - scroll bar height))
              var disTxt = parseInt(getStyle(obj2, attr)) - parseInt(getStyle(oDiv3_0, attr));
              var divTxt = (disTxt)*(divScroll/disScroll);
    
              // Move demove > 0 downward; Move up demove < 0 
              if (disMove > 0 && divScroll <= disScroll) {
                oDiv1_0.style[attr2] = divScroll + 'px';
                oDiv3_0.style[attr2] = divTxt + 'px';
                // Text area
              } else if (disMove <= 0 && divScroll >= 0) {
                // Both = 0; Only divScroll can get 0px
                oDiv1_0.style[attr2] = divScroll + 'px';
                oDiv3_0.style[attr2] = divTxt + 'px';
              } else {
                // Prevent moving too fast beyond the judgment range, and the scroll bar distance is less than 0
                if (disMove < 0) {
                  oDiv1_0.style[attr2] = 0;
                  oDiv3_0.style[attr2] = 0;
                } else if (disMove > 0) {
                  oDiv1_0.style[attr2] = disScroll + 'px';
                  oDiv3_0.style[attr2] = disTxt + 'px';              
                }
              }
              document.onmouseup = function () {
                this.onmousemove = '';
                this.onmouseup = '';
              }
              console.log(disMove,divScroll,disScroll,oldPos,divTxt)
            }
          }
    
          // oDiv2_0.onmousedown = function (ev) {
          //   var ev = ev||event;
          //   var disMouse = ev.clientX;
          //   var oldPos = this.offsetLeft;
          //   //Scroll range = scroll bar height + scroll box Height
          //   var disScroll = oDiv2.offsetWidth - oDiv2_0.offsetWidth -2; 
          // 
          //   document.onmousemove = function (ev) {
          //     ev = ev||event;
          //     //Moving distance
          //     var disMove = ev.clientX - disMouse;
          //     //Scroll bar TOP = scroll bar TOP + moving distance
          //     var divScroll = oldPos + disMove;
    
          //     //Text TOP = (text box height - viewing area height) * (scroll bar TOP / (scroll box height - scroll bar height))
          //     var divTxt= (oDiv3.offsetWidth - oDiv3_0.offsetWidth)*(divScroll / disScroll);
    
          //     //Move demove > 0 downward; Move up demove < 0 
          //     if (disMove > 0 && divScroll <= disScroll) {
          //       oDiv2_0.style.left = divScroll + 'px';
          //       oDiv3_0.style.left = divTxt + 'px';
          //       //Text area
          //     } else if (disMove <= 0 && divScroll >= 0) {
          //       //Both = 0; Only divScroll can get 0px
          //       oDiv2_0.style.left = divScroll + 'px';
          //       oDiv3_0.style.left = divTxt + 'px';
          //     } else {
          //       //Prevent moving too fast beyond the judgment range, and the distance of the scroll bar is less than 30
          //       if (disMove < 0 && divScroll < 30) {
          //         oDiv2_0.style.left = 0;
          //         oDiv3_0.style.left = 0;
          //       } else if (disMove > 0 && disScroll - divScroll < 30) {
          //         oDiv2_0.style.left = disScroll + 'px';
          //         oDiv3_0.style.left = oDiv3.offsetWidth - oDiv3_0.offsetWidth + 'px';              
          //       }
          //     }
          //     document.onmouseup = function () {
          //       this.onmousemove = '';
          //       this.onmouseup = '';
          //     }
          //     console.log(disMove,divScroll,disScroll,oldPos,divTxt)
          //   }
          //   return false; //  It can solve the text selection problem of chrome FireFox IE9
          // }
        }
        </script>
      </head>
      <body>
        <div id="div0">
          <div id="div1">
            <div id="div1_0"></div>
          </div>
          <div id="div2">
            <div id="div2_0"></div>
          </div>
          <div id="div3">
            <div id="div3_0">
              value			describe
    normal		Default. Whitespace is ignored by the browser.
    pre			Blank will be retained by the browser. It behaves in a similar way HTML Label in. inherit		Specifies that it should inherit from the parent element white-space The value of the property.
    nowrap		The text does not wrap, and the text continues on the same line until a label is encountered.
    pre-wrap	The whitespace sequence is retained, but line breaks are performed normally.
    pre-line	Merges whitespace sequences, but preserves line breaks.
    inherit		Specifies that it should inherit from the parent element white-space The value of the property.
    - Drag
      - Only horizontal drag
      - Limit range: the size of the range
      - Calculation scale: current value/Maximum
    - Control other objects
      - Example 1: controlling the size of an object
      - Example 2: control the transparency of objects
      - Example 3: control text scrolling
    - code:- Drag
    - Only horizontal drag
    - Limit range: the size of the range
    - Calculation scale: current value/Maximum
    - Control other objects
    - Example 1: controlling the size of an object
    - Example 2: control the transparency of objects
    - Example 3: control text scrolling
    - code:- code:- Drag
    - Only horizontal drag
    - Limit range: the size of the range
    - Calculation scale: current value/Maximum
    - Control other objects
            </div>
          </div>
        </div>
      </body>
    </html>
    

Ajax Basics

What is Ajax

  • What is a server

    • Web browsing process analysis
    • How to configure your own server program
  • What is?

    Ajax = Asynchronous JavaScript and XML

    (asynchronous JavaScript and XML)

    • No refresh data read
    • User registration, online chat room
      • Asynchronous, synchronous

Using Ajax

  • Basic: request and display static

    txt 
    

    file

    • Character set coding: uniform coding is required
    • Cache, block cache:
      • Cache according to URL: make the URL change all the time, and add a timestamp after the URL
  • Dynamic data: request a JS (or json) file. The obtained string needs to be parsed

    • Use of eval: parse into JS elements
    • DOM create element
  • Partial refresh: request and display some web page files

Ajax principles

  • HTTP request method
    • GET -- used to obtain data (such as browsing posts)
    • POST ---- used to upload data (e.g. user registration)
    • The difference between get and post
      • GET is to transfer data in the url: poor security, small capacity and cache
      • POST does not pass url: high security, large capacity (2G) and no cache

Ajax intermediate

Writing Ajax

  • Creating Ajax objects

    • ActiveXObject("Microsoft.XMLHTTP)
  • XMLHttpRequest()

    • Note: variables are properties of Window
      • Use undefined variable - error
    • Use undefined attribute - undefined
    • Use window If XMLHttpRequest returns true, it is chrome FF IE7,
      • Use window If activexobject ("Microsoft. Xmlhttp") returns true, it is IE6
  • Connect server

    • open(Method, file name, asynchronous transfer)
      
      • method: type of request; GET or POST, must be uppercase
      • URL: the location of the file on the server. For GET requests, to avoid caching, please add a unique ID to the URL
      • async: true (asynchronous) or false (synchronous)
  • Send request

    • send()
      
      • string: for POST requests only
  • Receive return value

  • Request status monitoring

    • onreadystatechange
      

      event

      • readyState property: request state

        • 0: not initialized. The open() method has not been called
        • 1: Start loading, called send() method, sending request
        • 2: Loading completed ` ` send() sending completed. All response contents have been received
        • 3: Parsing response content
        • 4: After the response content is parsed, it can be called on the client
      • Status attribute (http status code): request result, 200: success

      • responseText gets the response data in string form

        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        

POST request

A simple POST request:

example

xmlhttp.open("POST","/try/ajax/demo_post.php",true); xmlhttp.send();

If you need POST data like an HTML form, use setRequestHeader() to add an HTTP header. Then specify the data you want to send in the send() method:

example

xmlhttp.open("POST","/try/ajax/demo_post2.php",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Henry&lname=Ford");
methoddescribe
setRequestHeader(header,value)Add an HTTP header to the request. Header: Specifies the name of the header. Value: Specifies the value of the header
  • code:

    <html>
    <head>
    <script type="text/javascript">
    function Ajax(url, suc, err) {
        var oAjax = '';
        if (window.XMLHttpRequest) {
          // chrome FF IE9
          oAjax = new XMLHttpRequest;
        } else if (window.ActiveXObject) {
          oAjax = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (oAjax != '') {
          oAjax.onreadystatechange = state_change;
          oAjax.open('get', url, true);
          oAjax.send();
        } else {
          err();
        }
    
        function state_change() {
          if (oAjax.readyState === 4) {
            // complete
            if (oAjax.status === 200) {
              // success
              if (suc) {
                suc(oAjax.responseText);
              } else {
                return oAjax.responseText;
              }          
            } else if (oAjax.status === 404){
              console.log('url Error or does not exist');
            } else if (err){
              err();
            }
          } else if (oAjax.readyState === 0){
            console.log('uninitialized');
          } else if (oAjax.readyState === 1){
            console.log('Sending request');
          } else if (oAjax.readyState === 2){
            console.log('Processing request');
          } else if (oAjax.readyState === 3){
            console.log('Parsing');
          }
        }
      }
    window.onload = function () {
      var btn = document.getElementById('btn');
      btn.onclick = function () {
        Ajax('/api/blog/list', function (str) {
            // Use return data
            console.log('success')
            document.getElementById('T1').innerHTML = str;
        })
      }
    }
    
    </script>
    </head>
    
    <body>
    <div id="T1" style="border:1px solid black;height:40;width:300;padding:5"></div><br />
    <button id="btn">Click</button>
    </body>
    </html>
    

Ajax data

  • data type
    • What is data type - English / Chinese
    • XML / JSON
  • Character set (file encoding)
    • All files have the same character set

XMLHttpRequest

XMLHttpRequest is a built-in browser object that allows you to send HTTP requests using JavaScript.

Although it has the word "XML" in its name, it can manipulate any data, not just XML format. We can use it to upload / download files, track progress, etc.

Nowadays, we have a more modern method called fetch, which makes XMLHttpRequest abandoned to some extent.

In modern Web development, we still use XMLHttpRequest for the following three reasons:

  1. Historical reason: we need to support existing scripts that use XMLHttpRequest.
  2. We need to be compatible with older browsers and don't want to use polyfill (for example, to make the script smaller).
  3. We need to do something that fetch can't do at present, such as tracking the upload progress.

Do these words sound familiar? If so, please continue to read the following XMLHttpRequest. If you are not familiar with it, please read it first Fetch The content of this chapter.

XMLHttpRequest Foundation

XMLHttpRequest has two execution modes: synchronous and asynchronous.

Let's first look at the most commonly used asynchronous mode:

To send a request, there are three steps:

  1. Create XMLHttpRequest:

    let xhr = new XMLHttpRequest();
    

    This constructor has no parameters.

  2. Initialize it, usually after new XMLHttpRequest:

    xhr.open(method, URL, [async, user, password])
    

    This method specifies the main parameters of the request:

    • Method -- HTTP method. Usually "GET" or "POST".
    • URL -- the URL to request, usually a string, or URL Object.
    • async -- if explicitly set to false, the request will be processed synchronously, which we'll talk about later.
    • user, password -- login name and password for HTTP basic authentication (if required).

    Note that the open call, contrary to its name, does not establish a connection. It only configures requests, and network activity is turned on only with a send call.

  3. Send request.

    xhr.send([body])
    

    This method establishes the connection and sends the request to the server. The optional parameter body contains request body.

    Some request methods, such as GET, do not have a request body. There are also some request methods, such as POST, which uses the body to send data to the server. We'll see an example later.

  4. Listen for xhr events for responses.

    These three events are the most commonly used:

    • load -- when the request is completed (even if the HTTP status is 400 or 500, etc.) and the response has been completely downloaded.
    • error - when a request cannot be made, such as a network outage or an invalid URL.
    • progress -- triggered periodically during the download response, reporting how much has been downloaded.
    xhr.onload = function() {
      alert(`Loaded: ${xhr.status} ${xhr.response}`);
    };
    
    xhr.onerror = function() { // Triggered only if the request cannot be made at all
      alert(`Network Error`);
    };
    
    xhr.onprogress = function(event) { // Periodic trigger
      // event.loaded -- how many bytes have been downloaded
      // event.lengthComputable = true, when the server sends a content length header
      // event.total -- total bytes (if lengthComputable is true)
      alert(`Received ${event.loaded} of ${event.total}`);
    };
    

Here is a complete example. It loads / article/xmlhttprequest/example/load from the server and prints the loading progress:

// 1. Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();

// 2. Configure it: from URL / article // load GET-request
xhr.open('GET', '/article/xmlhttprequest/example/load');

// 3. Send requests over the network
xhr.send();

// 4. This function will be called when a response is received
xhr.onload = function() {
  if (xhr.status != 200) { // Analyze the HTTP status of the response
    alert(`Error ${xhr.status}: ${xhr.statusText}`); // For example, 404: Not Found
  } else { // Display results
    alert(`Done, got ${xhr.response.length} bytes`); // Response is the server response
  }
};

xhr.onprogress = function(event) {
  if (event.lengthComputable) {
    alert(`Received ${event.loaded} of ${event.total} bytes`);
  } else {
    alert(`Received ${event.loaded} bytes`); // No content length
  }

};

xhr.onerror = function() {
  alert("Request failed");
};

Once the server responds, we can receive the results in the following xhr attributes:

  • status

    HTTP status code (a number): 200404403, etc. If a non HTTP error occurs, it is 0.

  • statusText

    HTTP status message (a string): status code 200 corresponds to OK, 404 corresponds to Not Found, and 403 corresponds to Forbidden.

  • response (the old script may use responseText)

    Server response body.

We can also use the corresponding properties to specify the timeout:

xhr.timeout = 10000; // The timeout unit is ms, here is 10 seconds

If the request is not executed successfully within a given time, the request will be cancelled and the timeout event will be triggered.

URL search parameters

To add an image to the URL? We can use parameters such as name=value and ensure the correct coding URL Object:

let url = new URL('https://google.com/search');
url.searchParams.set('q', 'test me!');

// Parameter 'q' is encoded
xhr.open('GET', url); // https://google.com/search?q=test+me%21

Response type

We can use XHR Use the responsetype property to format the response:

  • "" (default) - the response format is string,
  • "text" -- the response format is string,
  • "ArrayBuffer" -- the response format is ArrayBuffer (for binary data, see ArrayBuffer, binary array),
  • "Blob" -- the response format is blob (for binary data, see Blob),
  • "Document" -- the response format is XML document (XPath and other XML methods can be used),
  • "JSON" -- the response format is JSON (automatic parsing).

For example, we get the response in JSON format:

let xhr = new XMLHttpRequest();

xhr.open('GET', '/article/xmlhttprequest/example/json');

xhr.responseType = 'json';

xhr.send();

// The response is {message ":" Hello, world! "}
xhr.onload = function() {
  let responseObj = xhr.response;
  alert(responseObj.message); // Hello, world!
};

Please note that:

In the old script, you might see XHR ResponseText, you will even see XHR Responsexml attribute.

They exist for historical reasons to get strings or XML documents. Now, we should be at XHR Set the format in responsetype, and then you can get the XHR as shown above Response.

readyState

The state of XMLHttpRequest will change as its processing progress changes. You can use XHR ReadyState to understand the current state.

standard All states mentioned in are as follows:

UNSENT = 0; // Initial state
OPENED = 1; // open called
HEADERS_RECEIVED = 2; // response header received
LOADING = 3; // Response is being loaded (received a packet)
DONE = 4; // Request complete

The XMLHttpRequest object transitions between them in the order of 0 → 1 → 2 → 3 →... → 3 → 4. State 3 is repeated every time a packet is received over the network.

We can use the readystatechange event to track them:

xhr.onreadystatechange = function() {
  if (xhr.readyState == 3) {
    // Loading
  }
  if (xhr.readyState == 4) {
    // Request complete
  }
};

You may find an event listener like readystatechange in very old code. It exists for historical reasons because there was no load or other events for a long time. Today, it has been replaced by the load/error/progress event handler.

Abort request (Aborting)

We can terminate the request at any time. Call XHR Abort():

xhr.abort(); // Termination request

It triggers the abort event and XHR Status changes to 0.

Synchronization request

If the third parameter async is set to false in the open method, the request will proceed synchronously.

In other words, JavaScript execution pauses at send() and resumes execution after receiving a response. This is a bit like the alert or prompt command.

The following is an example of rewriting. The third parameter of open is false:

let xhr = new XMLHttpRequest();

xhr.open('GET', '/article/xmlhttprequest/hello.txt', false);

try {
  xhr.send();
  if (xhr.status != 200) {
    alert(`Error ${xhr.status}: ${xhr.statusText}`);
  } else {
    alert(xhr.response);
  }
} catch(err) { // Replace onerror
  alert("Request failed");
}

This looks good, but synchronous calls are rarely used because they block JavaScript in the page until loading is complete. In some browsers, scrolling may not work properly. If a synchronization call takes too long to execute, the browser may suggest closing the "hanging" web page.

Many advanced features of XMLHttpRequest are not available in synchronous requests, such as making requests to other domains or setting timeouts. And, as you can see, there is no progress indication.

For these reasons, synchronization requests are rarely used and almost never used. We won't discuss it here.

HTTP-header

XMLHttpRequest allows you to send a custom header and read the header from the response.

HTTP header has three methods:

  • setRequestHeader(name, value)

    Set the request header with the given name and value. For example: XHR setRequestHeader('Content-Type', 'application/json'); Limitations of headers some headers are specially managed by the browser, such as Referer and Host. For a complete list, see standard . For user security and correctness of requests, XMLHttpRequest does not allow them to be changed. Another feature of not removing headerXMLHttpRequest is that setrequestheader cannot be revoked. Once the header is set, it cannot be undone. Other calls add information to the header, but do not overwrite it. For example: XHR setRequestHeader('X-Auth', '123'); xhr. setRequestHeader('X-Auth', '456'); // The header will be: / / X-Auth: 123, 456

  • getResponseHeader(name)

    Gets the header with the given name (except set cookie and set cookie2). For example: XHR getResponseHeader('Content-Type')

  • getAllResponseHeaders()

    Return all response header s except set cookie and set cookie 2. The header is returned as a single line, for example: cache control: Max age = 3153600 content length: 4260 content type: image / PNG date: SAT, 08 SEP 2012 16:53:16. The newline character between gmtheader is always "\ R \ n" (independent of the operating system), so we can easily split it into separate headers. Name and value are always separated by a colon followed by a space ":". This is the standard format. Therefore, if we want to get objects with name/value pairs, we need to process them with a little JavaScript code. Like this (assuming that if two headers have the same name, the latter will override the former): let headers = XHR getAllResponseHeaders() . split('\r\n') . reduce((result, current) => { let [name, value] = current.split(': '); result[name] = value; return result; }, {}); // headers['Content-Type'] = 'image/png'

POST,FormData

To create a POST request, we can use the built-in FormData Object.

The syntax is:

let formData = new FormData([form]); // To create an object, you can choose to get data from < form >
formData.append(name, value); // Attach a field

When we create it, we can choose to obtain data from a form. If necessary, we can append more fields, and then:

  1. xhr.open('POST', ...) —— Use the post method.
  2. xhr.send(formData) sends the form to the server.

For example:

<form name="person">
  <input name="name" value="John">
  <input name="surname" value="Smith">
</form>

<script>
  // Pre populate FormData from form
  let formData = new FormData(document.forms.person);

  // Attach a field
  formData.append("middle", "Lee");

  // Send it out
  let xhr = new XMLHttpRequest();
  xhr.open("POST", "/article/xmlhttprequest/post/user");
  xhr.send(formData);

  xhr.onload = () => alert(xhr.response);
</script>

Send the form in multipart / form data encoding.

Or, if we prefer JSON, we can use JSON Stringify and send as a string.

However, don't forget to set header content type: application / JSON. As long as it is available, many server-side frameworks can automatically decode JSON:

let xhr = new XMLHttpRequest();

let json = JSON.stringify({
  name: "John",
  surname: "Smith"
});

xhr.open("POST", '/submit')
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');

xhr.send(json);

The. send(body) method is like a very omnivorous animal. It can send almost any body, including Blob and BufferSource objects.

Upload progress

The progress event is triggered only during the download phase.

That is, if we POST some content, XMLHttpRequest first uploads our data (request body) and then downloads the response.

If we want to upload something big, then we will certainly be interested in tracking the upload progress. But XHR Onprogress doesn't work here.

Here is another object, which has no method. It is specially used to track upload events: XHR upload.

It generates events, similar to xhr, but xhr Upload triggers them only when uploading:

  • loadstart -- upload starts.
  • progress -- triggered periodically during upload.
  • abort - upload aborted.
  • Error -- non HTTP error.
  • load - upload completed successfully.
  • Timeout -- upload timeout (if timeout attribute is set).
  • Load - the upload is completed, regardless of success or error.

handler example:

xhr.upload.onprogress = function(event) {
  alert(`Uploaded ${event.loaded} of ${event.total} bytes`);
};

xhr.upload.onload = function() {
  alert(`Upload finished successfully.`);
};

xhr.upload.onerror = function() {
  alert(`Error during the upload: ${xhr.status}`);
};

This is a real example: file upload with progress indication:

<input type="file" onchange="upload(this.files[0])">

<script>
function upload(file) {
  let xhr = new XMLHttpRequest();

  // Track upload progress
  xhr.upload.onprogress = function(event) {
    console.log(`Uploaded ${event.loaded} of ${event.total}`);
  };

  // Tracking complete: whether successful or not
  xhr.onloadend = function() {
    if (xhr.status == 200) {
      console.log("success");
    } else {
      console.log("error " + this.status);
    }
  };

  xhr.open("POST", "/article/xmlhttprequest/post/upload");
  xhr.send(file);
}
</script>

Cross source request

XMLHttpRequest can use and fetch Cross source requests are made using the same CORS policy.

Like fetch, cookie s and HTTP authorization are not sent to other domains by default. To enable them, set XHR Withcredentials set to true:

let xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.open('POST', 'http://anywhere.com/request');
...

For more information about cross source header s, see Fetch: cross source request A chapter.

summary

Typical code of GET request using XMLHttpRequest:

let xhr = new XMLHttpRequest();

xhr.open('GET', '/my/url');

xhr.send();

xhr.onload = function() {
  if (xhr.status != 200) { // HTTP error?
    // Processing error
    alert( 'Error: ' + xhr.status);
    return;
  }

  // Get from XHR Response
};

xhr.onprogress = function(event) {
  // Report progress
  alert(`Loaded ${event.loaded} of ${event.total}`);
};

xhr.onerror = function() {
  // Handling non HTTP error s (e.g. network interruption)
};

In fact, there are many events in Modern norms There is a detailed list in (sorted by lifecycle):

  • loadstart -- request start.
  • progress -- when a response packet arrives, the whole response body is in the response.
  • abort -- call XHR abort() canceled the request.
  • Error - a connection error has occurred, for example, a domain error. HTTP errors such as 404 do not occur.
  • load - the request completed successfully.
  • Timeout -- the request was canceled because it timed out (only when timeout is set).
  • Loaded -- triggered after load, error, timeout or abort.

The error, abort, timeout and load events are mutually exclusive. Only one of them can happen.

The most common events are load complete (load), load failure (error), or we can use a single load handler and check the properties of the request object xhr to see what happened.

We also learned about another event: readystatechange. Due to historical reasons, it appeared long before the formulation of norms. Now we don't need to use it. We can replace it with a new event, but it can usually be found in the old code.

If we need to specifically track uploads, we should be at XHR Listen for the same event on the upload object.

JS object-oriented Foundation

What is the object

  • What is an object
    • What is a radio? Many components make up the whole and provide some functions
    • Object is a whole and provides some operations to the outside world
  • What is facing the object
    • When using an object, you only focus on the functions provided by the object, not on its internal details
    • Like JQuery
  • Object oriented is a general idea, which can be used not only in programming, but also in anything

Facing objects in JS

  • Characteristics of object oriented programming (OOP)
    • Abstract: grasp the core problem and extract the main features and relevant features
    • Encapsulation: it does not consider the internal implementation, but only the use of functions
    • Inheritance: inherits new objects based on existing objects
      • Polymorphic inheritance: having the characteristics of several parent objects at the same time
      • Polymorphism: JAVA and other strongly typed languages are commonly used, JS is not commonly used
  • Composition of objects
    • Method function: process, dynamic
      • Functions: not part of object
      • Methods: functions belonging to objects
    • Attribute - variable: state, static
      • Variables: not objects
      • Attributes: variables belonging to objects

The first object-oriented program

  • Adding methods and properties to objects

    • this
      

      Detailed explanation, event processing

      this
      

      Essence of

      • window
      • this -- who does the function belong to
    • Methods and properties cannot be attached to system objects at will, otherwise existing methods and properties will be overwritten

    • Object object: a blank system object

Factory mode

  • Factory mode

    • Create a class with a constructor
    • What are classes, objects (instances): molds and parts
    • Note: constructor / factory function
      • Functions to build objects
      • The constructor property returns constructor functions for all JavaScript variables.
  • Factory mode problems

    • No new
    • Repeated function definition: the contents of functions are the same but not equal, wasting a lot of system resources
  • Problem solving:

    Constructor plus

    new
    

    ,

    Then use the prototype

    Prototype
    

    Add for object

    method

    • new
      

      Did two things

      • Created a blank object for you: var this = new Object()
      • This blank object is returned for you: return this
    • new and this

Prototype: Prototype

  • What is the prototype

    • The prototype is a class. Modifying it can affect a class of elements
    • Add your own properties and methods to existing objects
  • Add Sum method for all arrays: Array prototype. Sum = function () {}

    • Add a method to an object, similar to an interline style
    • Add methods to the prototype, similar to class
  • Small defects in the prototype

    • Cannot restrict overrides
  • The difference between class and object

    • Class: template of production object

      Array
      
      • var arr = new Array()
    • Object: product arr

  • Summary: using constructors to add attributes and prototypes to add methods is called hybrid method to construct objects

  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Object oriented Foundation</title>
        <style>
        </style>
        <script>
          // Factory mode
          function CreatePerson(name, qq) {
            var obj = new Object();
    
            obj.name = name;
            obj.qq = qq;
            
            obj.showName = function () {
              console.log('name:', this.name);
            }
            obj.showQQ = function () {
              console.log('QQ: ', this.qq)
            }
    
            return obj;
          }
          var person = CreatePerson('zhangsan','212345678');
          person.showName();
          person.showQQ();
    
          // Use prototype
          function CreatePerson2(name, qq) {
            this.name = name;
            this.qq = qq;
          }
                  
          CreatePerson2.prototype.showName2 = function () {
            console.log('name:', this.name);
          }
          CreatePerson2.prototype.showQQ2 = function () {
            console.log('QQ: ', this.qq)
          }
          var people = new CreatePerson2('asdf','535');
          people.showName2();
          people.showQQ2();
        </script>
      </head>
      <body>
      </body>
    </html>
    

Object oriented programming

  • Constructing objects in a mixed manner
    • Mixed constructor / prototype approach
    • Mixed Constructor Function / Prototype Method
  • principle
    • Constructors: adding attributes
    • Prototype: addition method
  • Object naming conventions
    • Class name initial capital

JS face object instance

Object facing tabs

  • Rewrite the process oriented program into an object-oriented form

    • Principle: there can be no nested functions, but there can be global variables
    • Process:
      • onload: constructor
      • Global variables: attributes
      • Functions: Methods
    • Error correction:
      • this, event, closure, parameter passing
  • Objects and closures

    • Pass this through closure
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Object facing tabs</title>
        <style>
          .div2 {
            width: 200px;
            height: 200px;
            margin-top: 20px;
            position: relative;
          }
          .div1 {
            width: 200px;
            height: 20px;
            position: absolute;
            top: 0px;
          }
          ul {
            margin: 0;
            padding: 0;
            display: block;
            background: rgb(157, 234, 253);
            float: left;
            position: absolute;
            display: none;
            width: 200px;
            height: 200px;
          }
          .ul {
            display: block;
          }
          a {
            display: block;
            float: left;
            width: 49px;
            height: 20px;
            background: rgb(7, 184, 253);
            border-right: 1px solid rgb(255, 0, 234);
            text-decoration: none;
          }
          .a {
            background: rgb(32, 108, 221);
          }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
            return document.getElementById(id);
          }
        // Encapsulate getElementsByTagName
        function gets(obj,tagName) {
          return obj.getElementsByTagName(tagName)
        }
        // onload as constructor
        window.onload = function () {
          new TabSwitch('tabS')
        }
        // Construct an object
        function TabSwitch(id){
            var oDiv = get(id);
            var _this = this; // Avoid not finding this
            // Global variables as attributes
            this.aA = gets(oDiv,'a');
            this.aUl = gets(oDiv,'ul');
            // Show first element
            this.aUl[0].className = 'ul';
            // When the mouse covers a label, the corresponding element is displayed
            for (var i = 0; i < this.aUl.length; i++) {
              this.aA[i].index = i;
              this.aA[i].onmouseover = function () {
                // Pass the current this as a parameter_ This is passed in directly as the current this call
                _this.showTab(this); 
              }
            }
          }
          // The function is passed in as a method event and this as a parameter
          TabSwitch.prototype.showTab = function (aA) {
            // console.log(this); //  Currently this is the calling method_ this
            for (var i = 0; i < this.aA.length; i++) {
              this.aUl[i].className = '';
              this.aA[i].className = '';
            }
            this.aUl[aA.index].className = 'ul';
            this.aA.className = 'a';
          }
        </script>
      </head>
      <body>
        <div id="tabS">
          <div class="div1">
            <a href="javascript:;" id="a0">11</a>
            <a href="javascript:;" id="a1">22</a>
            <a href="javascript:;" id="a2">33</a>
            <a href="javascript:;" id="a3">44</a>
          </div>
          <div class="div2">
            <ul>
              <li>1</li>
            </ul>
            <ul>
              <li>2</li>
            </ul>
            <ul>
              <li>3</li>
            </ul>
            <ul>
              <li>4</li>
            </ul>
        </div>
        </div>
      </body>
    </html>
    

JS object-oriented advanced

Object oriented in Json mode

  • Wrap the method in a Json: a simple monomer is not suitable for multiple objects

    • Some people call it namespace
    • Put the same kind of methods together
  • code:

    var json = {
          name: 'zhangsan',
          QQ: 34543643,
          age: 23,
          showName: function () {
            console.log(this.name);
          },
          showQQ: function () {
            console.log(this.QQ);
          }
        }
        json.showName();
        json.showQQ();
    

Drag and drop and inheritance

  • Object oriented drag and drop

    • Rewrite the original drag and drop code, the same as below
  • Object inheritance

    • What is inheritance

      • A new class is obtained by slightly modifying the original class
      • It does not affect the function of the original class
    • instanceof
      

      Operators: returning

      true
      

      , if the object is an instance of an object type.

      • Check whether the object is an instance of a class

Use inheritance

  • Restricted drag class

    • Constructor camouflage

      • Inheritance of attributes

        • principle
      • Use of call

        function A() {
        	this.abc = 12;
        }
        A.rototype.show = {
        	alert(this.abc);
        }
        function B() {
        	A.call(this); // Use call to inherit the attribute and pass B into A function
        }
        // B.prototype = A.prototype; //  The shallow copy method is a reference to the same memory space
        for (var i in A.prototype) {
            B.prototype[i] = A.ptoyotype[i]; // Deep copy will not reference, but directly copy the content
        }
        var obj = new B();
        alert(obj.abc);
        obj.show.call(); // call is generally omitted
        
  • Prototype chain

    • Method inheritance
      • Principle: copy method refers to the same memory space
    • Method replication of overlay prototype
      • for in deep copy will not be referenced, and the content will be copied directly
  • Code: drag and drop to face the object and inherit a new object

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Object facing drag</title>
        <link rel="stylesheet" href="../reset.css">
        <style>
          #div1 {
            top: 100px;
            left: 100px;
            width: 200px;
            height: 200px;
            position: absolute;
            background-color: rgb(255, 0, 0);
          }
          #div2 {
            width: 200px;
            height: 200px;
            position: absolute;
            background-color: rgb(0, 255, 170)
          }
        </style>
        <script src="./lib/Drag.js"></script>
        <script src="./lib/LimitDrag.js"></script>
        <script>
    
        window.onload = function () {
          new Drag('div1');
          new LimitDrag('div2');
        }
        
        </script>
      </head>
      <body>
        <div id="div1">Normal drag</div>
        <div id="div2">Restricted drag</div>
      </body>
    </html>
    
    function Drag(id) {
      this.disX = '';
      this.disY = '';
      this.oDiv = document.getElementById(id);
      var _this = this;
      this.oDiv.onmousedown = function (ev) {
        _this.fnDown(ev);
        return false;
      };
    }
    Drag.prototype.fnDown = function (ev) {
      var ev = event||ev;
      var _this = this;
      // Mouse viewable area position - div left margin = mouse position within div
      this.disX = ev.clientX - this.oDiv.offsetLeft;
      this.disY = ev.clientY - this.oDiv.offsetTop;
      console.log(this.disX,'Viewable mouse X: ', ev.clientX, 'mouse Y: ',ev.clientY);
      document.onmousemove = function (ev) {
        _this.mouseMove(ev);
      }
      document.onmouseup = function (ev) {
        _this.mouseUp(ev);
      }
    }
    Drag.prototype.mouseMove = function(ev) {
        // The coordinates will not be updated until the Event object is continuously obtained
        var ev = event||ev;
        // console.log('visible area mouse X: ', ev.clientX,' mouse Y: ', ev.clientY);
        // Div position = new position in the visible area of the mouse - distance between the mouse and div
        this.oDiv.style.left = ev.clientX - this.disX + 'px';
        this.oDiv.style.top = ev.clientY - this.disY + 'px';
      }
    Drag.prototype.mouseUp = function () {
      document.onmousemove = '';
      document.onmouseup = ''; 
    }
    
    // Inheritance properties
    function LimitDrag(id) {
      Drag.call(this, id);
    }
    // Inheritance prototype
    for (var i in Drag.prototype) {
      LimitDrag.prototype[i] = Drag.prototype[i];
    }
    
    LimitDrag.prototype.mouseMove = function(ev) {
      // The coordinates will not be updated until the Event object is continuously obtained
      var ev = event||ev;
      // console.log('visible area mouse X: ', ev.clientX,' mouse Y: ', ev.clientY);
      // Div position = new position in the visible area of the mouse - distance between the mouse and div
      var l = ev.clientX - this.disX;
      var t = ev.clientY - this.disY; 
      if (l < 0) {
        l = 0;
      } else if (l > document.documentElement.clientWidth - this.oDiv.offsetWidth) {
        l = document.documentElement.clientWidth - this.oDiv.offsetWidth;
      }
      if ( t < 0) {
        t = 0;
      } else if (t > document.documentElement.clientHeight - this.oDiv.offsetHeight) {
        t = document.documentElement.clientHeight - this.oDiv.offsetHeight;
      }
      this.oDiv.style.top = t + 'px';
      this.oDiv.style.left = l + 'px';
    }
    

System object

  • Local object

    • What are local objects

    • Common objects: can be instantiated(

      new
      

      )

      • Object / Function / Array / String / Boolean / Number / Date / RegExp / Error
  • Built in object (static object): cannot be instantiated

    • What are local objects
      • Global (not available) / Math
  • Host object (object provided by browser)

    • DOM / BOM

JavaScript object definition

In JavaScript, almost "everything" is an object.

  • Booleans are objects (if defined with the new keyword)
  • Numbers are objects (if defined with the new keyword)
  • A string is an object (if defined with the new keyword)
  • Dates are always objects
  • Arithmetic is always an object
  • Regular expressions are always objects
  • Arrays are always objects
  • Functions are always objects
  • Objects are always objects

All JavaScript values, except the original values, are objects.

JavaScript raw value

Raw values are values that have no properties or methods.

The raw data type refers to the data that has the original value.

JavaScript defines five raw data types:

  • string
  • number
  • boolean
  • null
  • undefined

The original values are immutable (they are hard coded and therefore cannot be changed).

Assuming x = 3.14, you can change the value of X. However, you cannot change the value of 3.14.

valuetypenotes
"Hello"string"Hello" is always "hello"
3.14number3.14 always 3.14
truebooleanTrue is always true
falsebooleanFalse is always false
nullnull(object) null is always null
undefinedundefinedUndefined is always undefined

Objects are variables that contain variables

JavaScript variables can contain a single value:

var person = "Bill Gates";

Objects are also variables. But objects can contain many values.

Values are written as name: value pairs (names and values are separated by colons).

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};

JavaScript objects are collections of named values.

Object properties

Named values in JavaScript objects are called properties.

attributevalue
firstNameBill
lastNameGates
age62
eyeColorblue

Objects written in name value pairs are similar to:

  • Associative arrays in PHP
  • Dictionary in Python
  • Hash table in C
  • Hash mapping in Java
  • Hashing in Ruby and Perl

Object method

Methods are actions that can be performed on objects.

Object properties can be raw values, other objects, and functions.

Object methods are object properties that contain function definitions.

attributevalue
firstNameBill
lastNameGates
age62
eyeColorblue
fullNamefunction() {return this.firstName + " " + this.lastName;}

JavaScript objects are containers of named values called properties and methods.

You will learn more about methods in the next chapter.

Creating JavaScript objects

With JavaScript, you can define and create your own objects.

There are different ways to create objects:

  • Define and create a single object, using object text.
  • Define and create a single object through the keyword new.
  • Define an object constructor, and then create an object of construction type.

In ECMAScript 5, you can also use the function object Create() to create the object.

Use object literals

This is the easiest way to create objects.

With object text, you can define and create objects in a single statement.

Object text refers to the name: value pair in curly braces {} (such as age:62).

The following example creates a new JavaScript object with four properties:

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};

Spaces and line breaks are not important. Object definitions can span multiple lines:

var person = {
    firstName:"Bill",
    lastName:"Gates",
    age:62,
    eyeColor:"blue"
};

Use JavaScript keyword new

The following example also creates a new JavaScript object with four properties:

var person = new Object();
person.firstName = "Bill";
person.lastName = "Gates";
person.age = 50;
person.eyeColor = "blue"; 

The results of the above two examples are the same. You do not need to use new Object().

For simplicity, readability and execution speed, please use the first creation method (object text method).

JavaScript objects are mutable

Objects are mutable: they are addressed by reference, not by value.

If person is an object, the following statement will not create a copy of person:

var x = person;  // This does not create a copy of the person.

Object x is not a copy of person. It's person. X and person are the same object.

Any change to x will change person, because X and person are the same object.

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"}
 
var x = person;
x.age = 10;           // This will change both x.age and person age

**Note: * * JavaScript variables are not mutable. This is true only for JavaScript objects.

JavaScript object method

JavaScript method

JavaScript methods are actions that can be performed on objects.

JavaScript methods are properties that contain function definitions.

attributevalue
firstNameBill
lastNameGates
age62
eyeColorblue
fullNamefunction() {return this.firstName + " " + this.lastName;}

Methods are functions stored as object properties.

this keyword

In JavaScript, something called this refers to the object that owns the JavaScript code.

The value of this, when used in a function, is the object that "owns" the function.

Note that this is not a variable. It is a keyword. You cannot change the value of this.

Access object method

Create an object method using the following syntax:

methodName : function() { Code line }

Access the object method using the following syntax:

objectName.methodName()

You usually describe fullName() as a method of a person object and fullName as an attribute.

The fullName property is executed as a function after being called through ().

This example accesses the fullName() method of the person object:

name = person.fullName();

If you access the fullName property without using (), the function definition is returned:

name = person.fullName;

Using built-in methods

This example uses the toUpperCase() method of the String object to convert text to uppercase:

var message = "Hello world!";
var x = message.toUpperCase();

The value of x will be:

HELLO WORLD!

Add new method

Adding methods to objects is done inside the constructor function:

function person(firstName, lastName, age, eyeColor) {
    this.firstName = firstName;  
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.changeName = function (name) {
        this.lastName = name;
    };
}

The value of the changeName() function name is assigned to the lastName attribute of person.

Now you can try:

myMother.changeName("Jobs");

JavaScript object properties

Property refers to the value associated with the JavaScript object.

JavaScript objects are collections of unordered properties.

Properties can usually be modified, added, and deleted, but some properties are read-only.

Accessing JavaScript properties

The syntax for accessing object properties is:

objectName.property           // person.age

Or:

objectName["property"]       // person["age"]

Or:

objectName[expression]       // x = "age"; person[x]

The expression must evaluate to a property name.

person.firstname + " is " + person.age + " years old.";

person["firstname"] + " is " + person["age"] + " years old.";

JavaScript for... in loop

The JavaScript for... in statement iterates over the properties of an object.

for (variable in object) {
    Code to execute
}

The code block in the for... In loop executes once for each attribute.

Properties of the loop object:

var person = {fname:"Bill", lname:"Gates", age:62}; 

for (x in person) {
    txt += person[x];
}

Add new attribute

You can add new properties to existing objects by simple assignment.

Assuming that the person object already exists - you can add a new attribute to it:

person.nationality = "English";

You cannot use reserved words as property names (or method names). Please use JavaScript naming rules.

Delete attribute

Delete keyword to delete an attribute from an object:

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};
delete person.age;   // Or delete person["age"];

The delete keyword deletes both the value of the attribute and the attribute itself.

After deletion, the attribute cannot be used until it is added back.

The delete operator is designed for object properties. It has no effect on variables or functions.

The delete operator should not be used for predefined JavaScript object properties. Doing so will crash the application.

Attribute value

All properties have names. In addition, they have value.

Value is one of the properties of an attribute.

Other features include enumerable, configurable, and writable.

These features define how properties are accessed (readable or writable?)

In JavaScript, all attributes are readable, but only the value is modifiable (only when the attribute is writable).

(ECMAScript 5 has methods to get and set all attribute properties)

Prototype properties

JavaScript objects inherit the properties of their prototypes.

The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.

JavaScript object accessor

ECMAScript 5 (2009) introduced Getter and Setter.

Getter and Setter allow you to define object accessors (properties to be evaluated).

JavaScript Getter

This example uses the lang attribute to get the value of the language attribute.

example

// Create object:
var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "en",
  get lang() {
    return this.language;
  }
};

// Use getter s to display data from objects:
document.getElementById("demo").innerHTML = person.lang;

JavaScript Setter

This example uses the lang attribute to set the value of the language attribute.

example

var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "",
  set lang(lang) {
    this.language = lang;
  }
};

// Use setter to set object properties:
person.lang = "en";

// Display data from objects:
document.getElementById("demo").innerHTML = person.language;

Example 1

var person = {
  firstName: "Bill",
  lastName : "Gates",
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

// Use methods to display data from objects:
document.getElementById("demo").innerHTML = person.fullName();

Example 2

var person = {
  firstName: "Bill",
  lastName : "Gates",
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
};

// Use getter s to display data from objects:
document.getElementById("demo").innerHTML = person.fullName;

Example 1 accesses fullname: person. As a function fullName().

Example 2 accesses fullname: person. As an attribute fullName.

The second example provides a more concise syntax.

Ellipsis:

// Create object:
var person = {
  firstName: "Bill",
  lastName: "Gates",
  id: 12345,
  fullName() { // Omit fullName:fullName() {}
    return this.firstName + " " + this.lastName;
  }
}

// To display data in an object:
console.log(person.fullName());

Data quality

JavaScript ensures better data quality when using getter s and setter s.

In this example, use the lang attribute to return the value of the language attribute in uppercase:

// Create an object:
var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "en",
  get lang() {
    return this.language.toUpperCase();
  }
};

// Use getter s to display data from objects:
document.getElementById("demo").innerHTML = person.lang;
var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "",
  set lang(lang) {
    this.language = lang.toUpperCase();
  }
};

// Use getter s to set object properties:
person.lang = "en";

// Display data from objects:
document.getElementById("demo").innerHTML = person.language;

Why use Getter and Setter?

  • It provides a more concise syntax
  • It allows the syntax of attributes and methods to be the same
  • It ensures better data quality
  • Conducive to background work

A counter instance

example

var obj = {
  counter : 0,
  get reset() {
    this.counter = 0;
  },
  get increment() {
    this.counter++;
  },
  get decrement() {
    this.counter--;
  },
  set add(value) {
    this.counter += value;
  },
  set subtract(value) {
    this.counter -= value;
  }
};

// Operation counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;
Object.defineProperty()

Object. The defineproperty() method can also be used to add getters and setters:

// Define object
var obj = {counter : 0};

// Define setters
Object.defineProperty(obj, "reset", {
  get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
  get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
  set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
  set : function (value) {this.counter -= value;}
});

// Operation counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

JavaScript object constructor

Object type (blueprint) (class)

The examples in the previous chapter are limited. They create only a single object.

Sometimes we need to create "blueprints" for many objects of the same "type".

The way to create an "object type" is to use the object constructor function.

In the above example, the function Person() is the object constructor function.

You can create objects of the same type by calling the constructor function with the new keyword:

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = new Person("Bill", "Gates", 62, "blue");
var myMother = new Person("Steve", "Jobs", 56, "green");

this keyword

In JavaScript, something called this is the "owner" of the code.

The value of this, when used in an object, is the object itself.

In the constructor function, this has no value. It is a substitute for new objects. When a new object is created, the value of this will become the new object.

Note that this is not a variable. It is a keyword. You cannot change the value of this.

Add properties for constructor

Unlike adding a new property to an existing object, you cannot add a new property to an object constructor:

To add a new attribute to the constructor, you must add it to the constructor function:

Person.nationality = "English"; //The nationality of my friend is undefined

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.nationality = "English";
}

Add method for constructor

Your constructor function can also define methods:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.name = function() {return this.firstName + " " + this.lastName;};
}

Unlike adding a new method to an existing object, you cannot add a new method to an object constructor.

You must add a method to an object inside the constructor function.

Built in JavaScript constructor

JavaScript provides a constructor for the original object:

var x1 = new Object();    // A new Object object
var x2 = new String();    // A new String object
var x3 = new Number();    // A new Number object
var x4 = new Boolean();   // A new Boolean object
var x5 = new Array();     // A new Array object
var x6 = new RegExp();    // A new RegExp object
var x7 = new Function();  // A new Function object
var x8 = new Date();      // A new Date object

The Math() object no longer this column. Math is a global object. The new keyword is not available for math.

Faster way to create objects

As you can see above, JavaScript provides object versions of raw data types, strings, numbers, and Booleans. But there is no reason to create complex objects. The original value is much faster!

Use the object literal {} instead of new Object().

Use string literal '' instead of new String().

Use numeric literals instead of Number().

Use Boolean literals instead of new Boolean().

Please use array literal [] instead of new Array().

Use the mode literal instead of new RexExp().

Use the function expression () {} instead of new Function().

var x1 = {};            // New object
var x2 = "";            // New original string
var x3 = 0;             // New original value
var x4 = false;         // New original logical value
var x5 = [];            // New array object
var x6 = /()/           // New regular expression object
var x7 = function(){};  // New function object

JavaScript object prototype

We have realized that you cannot add a new attribute to an existing object constructor. If you need to add a new attribute to the constructor, you must add it to the constructor function

Prototype inheritance

All JavaScript objects inherit properties and methods from the prototype.

Date object inherits from date prototype. Array objects inherit from array prototype. The Person object inherits from Person prototype.

Object.prototype is at the top of the prototype inheritance chain:

Date objects, array objects, and Person objects all inherit from object prototype.

Using the prototype attribute

The JavaScript prototype property allows you to add new properties to the object constructor:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";

The JavaScript prototype attribute also allows you to add new methods to the object constructor:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
};

ECMAScript 5 features

These are the new features released in 2009:

  • "use strict" instruction
  • String.trim()
  • Array.isArray()
  • Array.forEach()
  • Array.map()
  • Array.filter()
  • Array.reduce()
  • Array.reduceRight()
  • Array.every()
  • Array.some()
  • Array.indexOf()
  • Array.lastIndexOf()
  • JSON.parse()
  • JSON.stringify()
  • Date.now()
  • Properties Getter and Setter
  • New object properties and methods

ECMAScript 5 syntax changes

  • Property access to string []
  • Trailing comma in array and object literals
  • Multiline string literal
  • Reserved word as attribute name

"use strict" instruction

"use strict" defines that JavaScript code should be executed in "strict mode".

For example, with strict patterns, undeclared variables cannot be used.

You can use strict mode in all programs. It can help you write clearer code, such as preventing you from using undeclared variables.

"use strict" is just a string expression. Old browsers don't throw errors if they don't understand them.

String.trim()

String.trim() removes white space characters at both ends of the string.

let str = "   \n\n    Hello World!  \n \x11 \r ?  \t\  ";
console.log(str.trim());

Array.isArray()

The isArray() method checks whether the object is an array.

let a = [],
  b = {};
console.log(Array.isArray(a), Array.isArray(b));

Array.forEach()

The forEach() method calls the function once for each array element. break, continue, etc. are not supported.

arr.forEach(function(elem, index, array) {
    if (arr[i] == 2) {
        continue
    }
    console.log(elem, index)
})

[1, 2, 3, 4, 5].forEach(function(i) {
    if (i === 2) {
        return;
    } else {
        console.log(i)
    }
})
  • The "original intention" of this code is to start traversal from the first element and end the traversal after encountering array item 2. Otherwise, the traversed numerical items will be printed. However, the fact surprises you because its output is 1, 3, 4, 5.

Array.map()

This example multiplies each array value by 2:

var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);

function myFunction(value) {
  return value * 2;
}

Array.filter()

This example creates a new array with elements with a value greater than 18:

var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);

function myFunction(value) {
  return value > 18;
}

Array.reduce()

This example determines the sum of all numbers in the array:

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);

function myFunction(total, value) {
  return total + value;
}

Array.reduceRight()

This example also determines the sum of all numbers in the array:

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);

function myFunction(total, value) {
  return total + value;
}

Array.every()

This example checks whether all values exceed 18:

var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);

function myFunction(value) {
  return value > 18;
}

Array.some()

This example checks whether some values exceed 18:

var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.some(myFunction);

function myFunction(value) {
  return value > 18;
}

Array.indexOf()

Retrieve the value of an element in an array and return its position:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");

Array.lastIndexOf()

Array.lastIndexOf() and array Indexof () is similar, but the retrieval starts at the end of the array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");

JSON.parse()

A common use of JSON is to receive data from a Web server.

Imagine that you receive this text string from the Web server:

'{"name":"Bill", "age":62, "city":"Seatle"}'

JavaScript function JSON Parse() is used to convert text to JavaScript objects:

var obj = JSON.parse('{"name":"Bill", "age":62, "city":"Seatle"}');

JSON.stringify()

A common use of JSON is to send data to a Web server.

When sending data to the Web server, the data must be a string.

Imagine that we have this object in JavaScript:

var obj = {"name":"Bill", "age":62, "city":"Seatle"};

Please use the JavaScript function JSON Stringify() converts it to a string.

var myJSON = JSON.stringify(obj);

The result will be a string that follows the JSON notation.

myJSON is now a string ready to be sent to the server:

var obj = {"name":"Bill", "age":62, "city":"Seatle"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

Date.now()

Date.now() returns the number of milliseconds since the zero date (January 1, 1970, 00:00:00:00).

var timInMSs = Date.now();

Date. The return of now () is the same as that of getTime() on the date object.

Properties Getter and Setter

ES5 allows you to define object methods using syntax similar to getting or setting properties.

This example creates a getter for the property named fullName:

// Create object:
var person = {
  firstName: "Bill",
  lastName : "Gates",
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
};

// Use getter s to display data from objects:
document.getElementById("demo").innerHTML = person.fullName;

This example creates a setter and a getter for language attributes:

var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "NO",
  get lang() {
    return this.language;
  },
  set lang(value) {
    this.language = value;
  }
};

// Use setter to set object properties:
person.lang = "en";

// Use getter s to display data from objects:
document.getElementById("demo").innerHTML = person.lang;

This example uses a setter to ensure that the uppercase of the language is updated:

var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "NO",
  set lang(value) {
    this.language = value.toUpperCase();
  }
};

// Use setter to set object properties:
person.lang = "en";

// Display data from objects:
document.getElementById("demo").innerHTML = person.language;

New object properties and methods

Object.defineProperty() is a new object method in ES5.

It allows you to define object properties and / or change the values and / or metadata of properties.

// Create object:
var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "NO", 
};

// Change properties:
Object.defineProperty(person, "language", {
  value: "EN",
  writable : true,
  enumerable : true,
  configurable : true
});

// Enumeration properties
var txt = "";
for (var x in person) {
  txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;

The next example is the same code, but it hides the language attribute in the enumeration:

// Create object:
var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "NO", 
};

// Change properties:
Object.defineProperty(person, "language", {
  value: "EN",
  writable : true,
  enumerable : false,
  configurable : true
});

// Enumeration properties
var txt = "";
for (var x in person) {
  txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;

This example creates a setter and getter to ensure the uppercase update of the language:

// Create object:
var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "NO"
};

// Change properties:
Object.defineProperty(person, "language", {
  get : function() { return language },
  set : function(value) { language = value.toUpperCase()}
});

// Change language
person.language = "en";

// Display language
document.getElementById("demo").innerHTML = person.language;

ECMAScript 5 object method:

ES5 New object method

// Add or change object properties
Object.defineProperty(object, property, descriptor)

// Add or change multiple object properties
Object.defineProperties(object, descriptors)

// Access properties
Object.getOwnPropertyDescriptor(object, property)

// Returns all attributes as an array
Object.getOwnPropertyNames(object)

// Returns enumerable properties as an array
Object.keys(object)

// Access prototype
Object.getPrototypeOf(object)

// Prevent adding attributes to objects
Object.preventExtensions(object)

// Returns true if a property can be added to an object
Object.isExtensible(object)

// Prevent changing object properties (not values)
Object.seal(object)

// Returns true if the object is sealed
Object.isSealed(object)

// Prevent any changes to objects
Object.freeze(object)

// Returns true if the object is frozen
Object.isFrozen(object)

Property access to strings

The charAt() method returns the characters of the specified index (position) in the string:

var str = "HELLO WORLD";
str.charAt(0);            // Return to H

ECMAScript 5 allows attribute access to Strings:

var str = "HELLO WORLD";
str[0];                   // Return to H

Property access to strings can be a bit unpredictable.

Trailing commas

ECMAScript 5 allows trailing commas in object and array definitions:

Object instance

person = {
  firstName: "Bill",
  lastName: " Gates",
  age: 62,
}

Array instance

points = [
  1,
  5,
  10,
  25,
  40,
  100,
];

Warning!!!

Internet Explorer 8 will crash.

Trailing commas are not allowed in JSON.

JSON object:

// Allow:
var person = '{"firstName":"Bill", "lastName":"Gates", "age":62}'
JSON.parse(person)

// not allow:
var person = '{"firstName":"Bill", "lastName":"Gates", "age":62,}'
JSON.parse(person)

JSON array:

// Allow:
points = [40, 100, 1, 5, 25, 10]

// not allow:
points = [40, 100, 1, 5, 25, 10,]

Multiline string

ECMAScript 5 allows multiple lines of string text (literal) if backslash escape is used:

"Hello \
Kitty!";

\The method may not be generally supported.

Older browsers may handle spaces around backslashes differently.

Some older browsers do not allow spaces after the \ character.

A safer way to decompose string literals is to use string addition:

"Hello " + 
"Kitty!";

Reserved word as attribute name

ECMAScript 5 allows reserved words as attribute names:

var obj = {name: "Bill", new: "yes"}

ES5 new object methods

// Add or change object properties
Object.defineProperty(object, property, descriptor)

// Add or change multiple object properties
Object.defineProperties(object, descriptors)

// Access properties
Object.getOwnPropertyDescriptor(object, property)

// Returns all properties as an array
Object.getOwnPropertyNames(object)

// Returns all enumerable properties as an array
Object.keys(object)

// Access prototype
Object.getPrototypeOf(object)

// Prevent adding properties to objects
Object.preventExtensions(object)

// Returns true if a property can be added to an object
Object.isExtensible(object)

// Prevent changing object properties (not values)
Object.seal(object)

// Returns true if the object is sealed
Object.isSealed(object)

// Prevent any changes to objects
Object.freeze(object)

// Returns true if the object is frozen
Object.isFrozen(object)

Change attribute value

Object.defineProperty(object, property, {value : value})

This example changes the attribute value:

var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "EN" 
};

// change attributes
Object.defineProperty(person, "language", {value : "ZH"});

Change metadata

ES5 allows you to change the following attribute metadata:

writable : true      // The attribute value can be modified
enumerable : true    // Property enumerable
configurable : true  // Properties can be reconfigured
writable : false     // The property value cannot be modified
enumerable : false   // Properties cannot be enumerated
configurable : false // Property is not reconfigurable

ES5 allows you to change getter s and setter s:

// Define getter
get: function() { return language }
// Define setter
set: function(value) { language = value }

This example makes the language read-only:

Object.defineProperty(person, "language", {writable:false});

This example makes the language enumerable:

Object.defineProperty(person, "language", {enumerable:false});

List all attributes

This example lists all the properties of the object:

var person = {
  firstName: "Bill",
  lastName : "Gates"
  language : "EN" 
};

Object.defineProperty(person, "language", {enumerable:false});
Object.getOwnPropertyNames(person);  // Returns an array of properties

List enumerable properties

This example only lists all enumerable properties of the object:

var person = {
  firstName: "Bill",
  lastName : "Gates"
  language : "EN" 
};

Object.defineProperty(person, "language", {enumerable:false});
Object.keys(person);  // Returns an array of enumerable properties

Add attribute

This example adds a new attribute to the object:

// create object
var person = {
  firstName: "Bill",
  lastName : "Gates",
  language : "EN"
};

// Add attribute
Object.defineProperty(person, "year", {value:"2008"});

Add Getter and Setter

Object. The defineproperty() method can also be used to add getters and setters:

// create object
var person = {firstName:"Bill", lastName:"Gates"};

// Define getter
Object.defineProperty(person, "fullName", {
  get : function () {return this.firstName + " " + this.lastName;}
});

BOM application

BOM basis

  • Open and close windows

    • open(url, Open mode)
      

      :

      open('ablout.blank', '_blank')
      
      • Example: function of running code in the page
    • close(url, Open mode)
      

      :

      window.close()
      

      Close current window

      • Example: prompt questions when closing
        • You can only close your own open window
  • Common properties

    • window.navigator.userAgent
      
      • navigator: contains a lot of information
      • userAgent: browser information
    • window.location
      
      • href: current web page address
      • hostname: host domain name
      • pathname: page path and file name
      • port: port
      • Protocol: http protocol
      • assign: load new document, url
    • window.history
      
      • back(): back
      • forward(): forward
      • go(): a page in history, - 1 is used to jump back after login

Dimensions and coordinates

  • Window size, workspace size
    • Visual area size
      • document.documentElement.clientWidth
      • document.documentElement.clientHeight
    • Rolling distance
      • document.body.scrollTop: older versions of chrome and IE without DOCTYPE declaration
      • document.documentElement.scrollTop: IE FF
      • Perfectly get the assignment phrase of scrolltop: VAR scrolltop = document documentElement. scrollTop || window. pageYOffset || document. body. scrollTop;

Common methods and events

  • System dialog

    • Warning box: alert("content"), no return value
    • Select the box: confirm("content of the question"), and return to boolean
    • Input box: prompt(), return string or null
  • Common events of window object

    • onload: occurs after the page is loaded
    • onscroll: occurs when a page scrolls
    • onresize: the event occurs when the window or frame is resized
    • Example: back to top button, sidebar ad
      • Flicker problem
        • position:fixed for useragent > IE6;
        • Useragent < IE6 motion;
  • code:

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Bom application</title>
        <style>
          body {
            height: 2000px;
          }
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
    
        window.onload = function () {
          // var text =  document.write('New page ');
          var btn = get('btn');
          var btn2 = get('btn2');
          btn.onclick = function () {
            window.open('27.BOM application.html','_blank');
          }
          btn2.onclick = function () {
            window.close();
          }
    
    
          window.onscroll = function () {
            var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
            console.log('scrollTop:',scrollTop);
          }
          
          console.log(window.navigator.userAgent);
          console.log(window.location.href);
          // alert('0');
          // confirm('yes?');
          // prompt('');
    
          window.onresize = function () {
            var cliHei = document.documentElement.clientHeight;
            var cliWid = document.documentElement.clientWidth;
            console.log('Viewing area height and width:',cliHei, cliWid)
          }
        }
        </script>
    </head>
      <body>
        <input type="button"  id="btn" value="Open web page">
        <input type="button"  id="btn2" value="Close web page">
      </body>
    </html>
    

COOKIE foundation and Application

What is a cookie

  • The page is used to save information

    • For example, automatically log in and remember the user name
  • cookie
    

    Characteristics of

    • All pages in the same website share a set of cookie s
    • Limited quantity and size
    • Expiration time
  • Used in JS

    cookie
    
    • document.cookie

Using cookie s

  • Set cookie s

    • Format: name = value

    • Assignment will not be overwritten

    • Expiration time: expires = time

      • Set the expiration time of the previous cookie data. expires is placed after the data:
        • document.cookie = 'password=123;expires='+ oDate;
      • Use of date objects
    • Encapsulation function

      // Encapsulate setCookie function
            function setCookie(name, value, iTime) {
              var oDate = new Date();
              oDate.setTime(oDate.getTime() + iTime); // millisecond
              document.cookie = name + '=' + value + ';expires=' + oDate;
            }
            setCookie('username', 'Zhang San', 1000*60*60);
      
  • Read cookie s

    • String segmentation

      // Encapsulate getCookie function
       getCookie(name) {
              var arr = document.cookie.split('; ');
              for (var i in arr) {
                var arr2 = arr[i].split('=');
                if (arr2[0] === name){
                  return arr2[1];
                }
              }
              return '';
            }
            console.log(getCookie('username'));
      
  • Delete cookie

    • Has expired

      // Encapsulating the removeCookie function
      function removeCookie(name) {
              setCookie(name, '', -1)
            }
            removeCookie('username');
      
  • Example: use a cookie to record the last login user name

    • When submitting: record user name

    • window.onload: read user name

    • code:

      <!DOCTYPE html>
      <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
          <title>28.1.After landing cookie Read user name</title>
          <style>
          </style>
          <script>
            // Encapsulate setCookie function
            function setCookie(name, value, iTime) {
              var oDate = new Date();
              oDate.setTime(oDate.getTime() + iTime*1000*60*60);
              document.cookie = name + '=' + value + ';expires=' + oDate;
            }
            // Encapsulate getCookie function
            function getCookie(name) {
              var arr = document.cookie.split('; ');
              for (var i in arr) {
                var arr2 = arr[i].split('=');
                if (arr2[0] === name){
                  return arr2[1];
                }
              }
              return '';
            }
            // Encapsulating the removeCookie function
            function removeCookie(name) {
              setCookie(name, '', -1)
            }
      
            window.onload = function () {
              var oUser = document.getElementById('username');
              var oPasswd = document.getElementById('passwd');
              var oBtn_sub = document.getElementById('btn_sub');
              if (getCookie('username')) {
                oUser.value = getCookie('username');
              }
              oBtn_sub.onclick = function () {
                setCookie("username", oUser.value, 1);
                setCookie("passwd", oPasswd.value, 1);
              }
            }
          </script>
        </head>
        <body>
          <form action="28.1.After landing cookie Read user name.html" method="GET">
          <input type="text" name="username" id="username">
          <input type="text" name="passwd" id="passwd">
          <input type="submit" name="" id="btn_sub" value="Sign in">
          </form>
        </body>
      </html>
      

Regular expressions in JS

Regular expression basis

  • Review string operations:

    var str = 'asdf1234';
    
    • Search: find location str.search('3 ')

    • substring
      

      : get substring,

      • Intercept a certain string, excluding the end bit: str.substring(2,5)
      • Get the string after the starting point: str.substring(2)
    • charAt: get a string str.charAt(2)

    • Split: split a string str.split('-')

  • Find all the numbers in the string

    • Complete with traditional string operation
    • Complete with regular expressions
  • What is a regular expression

    • What is regular?

      • Rules, patterns
    • Powerful string matching tool

    • It is a kind of writing that is difficult for human beings to understand

    • RegExp
      

      object

      • JS style: new regexp ("a", "I")
      • perl style: / a/i

String and regular fit

  • Search: string search, return position or - 1

    • Return to where it appears
    • Ignore case: i: ignore
    • Determine browser type
  • match: get the matched item and return the element or

    • Quantifier: + (several)
    • Quantifier changes: \ d (a group of single numbers) \ d \ d (a group of two numbers) and \ d + (several consecutive numbers)
    • global match: g: global
    • Example: find all the numbers
  • replace(reg/str,replacement): replace all matches

    • Returns the replaced string
    • Example: sensitive word filtering
  • reg. Problem with test()

    • Once true, once false The reason is g in the regular expression, so that after the search process, if the match is successful, the last position will be recorded. If the match is unsuccessful, it will return to zero
    // Manually reset the position to zero to prevent this "error":
    var re = /^\w$/g;
    re.test('a'); //Return true
    re.lastIndex = 0; //Location of zeroing search
    re.test('b'); //Return true
    
    // Or we can simply remove g:
    var re = /^\w$/;
    re.test('a'); //Return true
    re.test('b'); //Return true
    
  • The exec() method is used to retrieve a match for a regular expression in a string.

    RegExpObject.exec(string)
    
    parameterdescribe
    stringRequired. String to retrieve

    If exec() finds a matching text, it returns an array of results. Otherwise, null is returned. The 0th element of this array is the text that matches the regular expression, the first element is the text that matches the first sub expression of RegExpObject (if any), the second element is the text that matches the second sub expression of RegExpObject (if any), and so on. In addition to the array element and the length attribute, the exec() method returns two attributes. The index attribute declares the position of the first character of the matching text. The input attribute stores the retrieved string. We can see that when calling the exec() method of a non global RegExp object, the returned array is the same as the calling method string The array returned by match () is the same.

    However, when RegExpObject is a global regular expression, the behavior of exec() is slightly more complex. It starts retrieving the string at the character specified by the lastIndex property of RegExpObject. When exec() finds the text that matches the expression, after matching, it will set the lastIndex property of RegExpObject to the next position of the last character of the matching text. That is, you can iterate through all matching text in the string by calling the exec() method repeatedly. When exec() finds no more matching text, it returns null and resets the lastIndex property to 0.

    **Important: * * if you want to start retrieving a new string after completing a pattern match in a string, you must manually reset the lastIndex property to 0.

    **Hint: * * Please note that whether RegExpObject is in global mode or not, exec() will add the full details to the array it returns. This is exec () and string Match (), which returns much less information in global mode. Therefore, we can say that calling the exec () method repeatedly in the loop is the only way to obtain the complete pattern matching information of the global pattern.

    var str = "Visit W3School"; 
    var patt = new RegExp("W3School","g");
    var result;
    
    while ((result = patt.exec(str)) != null)  {
      document.write(result);
      document.write("<br />");
      document.write(patt.lastIndex);
     }
    

character string

  • Any character:

    []
    

    Square brackets (metacharacters)

    • [abc]
      
      • Example: a[usb]t: obt ost out
  • Range

    • [a-z]
      
      [0-9]
      
      • Example: id[0-9]: id0 id5
  • exclude

    • [^a]
      
      • Example: o[^0-9]: oat ``o?t ot
  • combination

    • [a-z0-9A-Z]
  • Example: stealing Novels

    • Filter HTML tags,
      • Regular greedy feature, filtering from the longest content
      • Custom innerText method
    • Code: same as below
  • Escape character

    • (DOT): any character except newline
    • .+[\s\S].+: Any character
    • \d (number): [0-9]
    • \w (number, English, underline): [a-z0-9_]
    • \s (white space character): []
    • \D (except numbers): [^ 0-9]
    • \W (except numbers and English underscores): [^ a-z0-9]
    • \S (except white space characters): [^]
  • Line beginning and end

    • ^: line beginning
    • $: end of line
  • logic

    • |: perform a logical or operation on two matching conditions

classifier

  • What is a quantifier

    • {n} : just n times
    • {n,m} occurs at least N times and at most m times
    • Example: find QQ number
  • Common quantifiers

    • {n,} at least N times, no upper limit

    • *Any time {0,} can be 0 times, which is not recommended

    • ? Zero or one {0,1}

      fixed telephone:010-23456789-1234 Or 23456789
      (0\d{2,3}-)?[1-9]\d{7}(-\d{1,5})?
      
    • +Once or any time {1,}

    • {n} Exactly n times

Common regular examples

  • Form verification instance

    • Check mailbox
      • Line beginning and end
  • <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Regular expression application</title>
        <style>
        </style>
        <script>
        // Encapsulate getElementById function
        function get(id) {
          return document.getElementById(id);
        }
        
        var arr = [];
        var temp = '';
        var str = 'asdf-1234-as24-q2e4';
        // console.log(str.search('3'));
        // console.log(str.substring(2,5));
        // console.log(str.substring(2));
        // console.log(str.charAt(2));
        // console.log(str.split('-'));
        for (var i in str) {
          if(str.charAt(i) >= 0 && str.charAt(i) <= 9) {
            // arr.push(str.charAt(i));
            temp += str.charAt(i);
          } else if (temp) {
            arr.push(temp);
            temp = '';
          }
        }
        arr.push(temp);
        temp = '';
        console.log('String method:',arr);
        console.log('match method:',str.match(/\d+/g));
    
        
        window.onload = function () {
          var btn = get('btn');
          var btn2 = get('btn2');
          var btn3 = get('btn3');
          var btn4 = get('btn4');
          var text = get('text');
          var text2 = get('text2');
    
          // Check mailbox
          // Get the content and find out those that do not comply with the rules
          // abc_123@abc123.abc
          btn.onclick = function () {
            var reg = /^\w+@{1,}[0-9a-z]+\.{1,}[a-z]+$/i;
            var txt = text.value;
            text2.value = '';
            txt.search(reg);
            console.log(txt.match(reg),reg.test(txt));
            if (reg.test(txt)){
              text2.value = txt.match(reg);
            }
          }
          // Filter HTML tags
          btn2.onclick = function () {
            var reg = /<[^<>]+>/g;
            txt = text.value.replace(reg,'')
            text2.value = txt;
          }
          // Detect fixed telephone
          btn3.onclick = function () {
            var reg = /^(0\d{2,3}-)?[1-9]\d{7}(-\d{1,5})?$/;
            var txt = text.value;
            text2.value = '';
            txt.search(reg);
            console.log(txt.match(reg),reg.test(txt));
            if (reg.test(txt)){
              text2.value = txt.match(reg);
            }
          }
          // Detect password strength
          // Digital low
          // Numbers in English or symbols
          // Numeric English symbol high
          btn4.onclick = function () {
            var regLow = /\d+/;
            var regMid = /\d+[a-z]+/i;
            var regHei = /\d+[a-z_]+\S+/i;
            var txt = text.value;
            if (regHei.test(txt)) {
              text2.value = 'high';
            } else if (regMid.test(txt)) {
              text2.value = 'in';
            } else if (regLow.test(txt)) {
              text2.value = 'low';
            }
          }
        }
        </script>
      </head>
      <body>
        <textarea name="" id="text" cols="30" rows="10"></textarea>
        <div>
          <input type="button" value="Detect mailbox" id="btn">
          <input type="button" value="filter HTML label" id="btn2">
          <input type="button" value="Test phone" id="btn3">
          <input type="button" value="Detect password" id="btn4">
        </div>
        <textarea name="" id="text2" cols="30" rows="10"></textarea>
      </body>
    </html>
    

RegExp object

RegExp objects represent regular expressions, which are powerful tools for performing pattern matching on strings.

Direct quantity grammar

/pattern/attributes

Syntax for creating RegExp objects:

new RegExp(pattern, attributes);

parameter

The parameter pattern is a string that specifies the pattern of the regular expression or other regular expressions.

The parameter attributes is an optional string containing attributes "g", "i" and "m", which are used to specify global matching, case sensitive matching and multiline matching respectively. Before ECMAScript standardization, the M attribute is not supported. If pattern is a regular expression instead of a string, this parameter must be omitted.

Return value

A new RegExp object with the specified mode and flag. If the parameter pattern is a regular expression instead of a string, the RegExp() constructor will create a new RegExp object with the same pattern and flag as the specified RegExp.

If RegExp() is called as a function without the new operator, its behavior is the same as that when it is called with the new operator, except that when pattern is a regular expression, it only returns pattern instead of creating a new RegExp object.

Throw

Syntax error - throw this exception if pattern is not a legal regular expression or attributes contain characters other than "g", "i" and "m".

TypeError - this exception is thrown if the pattern is a RegExp object but the attributes parameter is not omitted.

Modifier

Modifier describe
iPerforms a case insensitive match.
gPerform a global match (find all matches instead of stopping after the first match is found).
mPerform multiline matching.

square brackets

Square brackets are used to find characters in a range:

expressiondescribe
[abc]Find any characters between square brackets.
[^abc]Find any characters that are not between square brackets.
[0-9]Find any number from 0 to 9.
[a-z]Find any character written from small a to lowercase z.
[A-Z]Find any character from uppercase A to uppercase Z.
[A-z]Find any character from uppercase A to lowercase z.
[adgk]Finds any character in a given set.
[^adgk]Finds any character outside the given set.
(red|blue|green)Find any specified options.

Metacharacter

Metacharacter s are characters with special meanings:

Metacharacterdescribe
.Finds a single character, except line breaks and line terminations.
\wFind word characters.
\WFind non word characters.
\dFind a number.
\DFind non numeric characters.
\sFind white space characters.
\SFind non white space characters.
\bMatch word boundaries.
\BMatches non word boundaries.
\0Find NUL characters.
\nFind line breaks.
\fFind page feed.
\rFind carriage return.
\tFind tabs.
\vFind vertical tabs.
\xxxFind the characters specified in octal number xxx.
\xddFinds the character specified in hexadecimal number dd.
\uxxxxFinds Unicode characters specified in hexadecimal number xxxx.

classifier

classifierdescribe
n+Matches any string that contains at least one n.
n*Matches any string containing zero or more n's.
n?Matches any string containing zero or one n.
n{X}Matches a string containing a sequence of X n.
n{X,Y}Matches a string containing a sequence of X to Y n.
n{X,}Matches a string containing a sequence of at least X n.
n$Matches any string ending in n.
^nMatches any string that starts with n.
?=nMatches any string followed by the specified string n.
?!nMatches any string that is not immediately followed by the specified string n.

RegExp object properties

attributedescribeFFIE
globalWhether the RegExp object has a flag g.14
ignoreCaseWhether the RegExp object has a flag i.14
lastIndexAn integer indicating the character position to start the next match.14
multilineWhether the RegExp object has a flag m.14
sourceThe source text of the regular expression.14

RegExp object method

methoddescribeFFIE
compileCompile regular expressions.14
execRetrieves the value specified in the string. Returns the value found and determines its location.14
testRetrieves the value specified in the string. Returns true or false.14

Method of String object supporting regular expression

methoddescribeFFIE
searchRetrieves the value that matches the regular expression.14
matchA match was found for one or more regular expressions.14
replaceReplace substrings that match regular expressions.14
splitSplits a string into an array of strings.14

JS Template template engine

https://www.jb51.net/article/100095.htm

1. Characteristics

(1) Excellent performance, and the execution speed is usually more than 20 times that of Mustache and tmpl (performance test)

(2) Support runtime debugging, and accurately locate the statement where the exception template is located (demonstration)

(3) . friendly support for NodeJS Express

(4) . safe. By default, the output is escaped and the compiled code is run in the sandbox (the Node version can safely execute the template uploaded by the user)

(5) . support include statement

(6) . the template can be loaded by path on the browser side (details)

(7) Supports precompiling and can convert the template into a very compact js file

(8) . the template statement is concise and does not need prefix to reference data. The concise version and native Syntax version are optional

(9) Support all popular browsers

2. Grammar

(1) , use

Refer to the engine version of concise syntax, for example: < script SRC = ". / lib / template-web. JS" > < / script >

(2) , expression

The statement wrapped with {{and}} symbols is the logical expression of the template.

template('test', data): rendering

(3) , output expression

Encoding (escaping) output of content: {{content}} output without encoding (escaping): {{#content}} encoding can prevent HTML strings in data and avoid XSS attacks.

(4) Conditional expression

{{if admin}} 
 <p>admin</p> 
{{else if code > 0}} 
 <p>master</p> 
{{else}} 
 <p>error!</p> 
{{/if}} 

(5) , traversal expression

Either array or object can be traversed with each.

{{each list as value index}} 
 <li>{{index}} - {{value.user}}</li> 
{{/each}} 
// It can also be abbreviated: $refers to the variable in the current function
{{each list}} 
 <li>{{$index}} - {{$value.user}}</li> 
{{/each}} 

(6) The template contains expressions

Used to embed sub templates.

{{include 'template_name'}}

The sub template shares the current data by default. You can also specify data: {{include 'template_name' news_list}}

(7) . auxiliary methods

Use template defaults. imports. Dateformat = function (arg1, arg2) {} register public helper method:

template.defaults.imports.dateFormat = function(arg1,arg2) { 
 // .. 
 return value; 
}); 

The method used in the template: {time | dateformat: 'yyyy MM DD HH: mm: Ss'}} supports the use of incoming parameters and nesting: {time | say:' CD '| UBB | link}}

3. Instance

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <script src="./lib/template-web.js"></script>
</head>

<body>
  <div id="content"></div>
  <script id="test" type="text/html">
    <div>
      <!-- Output expression -->
      <p>{{name}}</p>
      <!-- No escape output -->
      <p>{{#value}}</p>

      <!-- Conditional expression -->
      {{if bool}}
      <p>{{bool}}</p>
      {{/if}}
      {{if num < 1 }}
      <p>'num < 1'</p> {{else}} <p>error!</p>
      {{/if}}

      <!-- Traversal expression array -->
      <p>Traversal expression array</p>
      {{each list as value index}}
      <li>{{index}}: {{value}}</li>
      {{/each}}
      <!-- $Abbreviation $ Refers specifically to the variables in the current function -->
      <p>$Abbreviation</p>
      {{each list}}
      <li>{{$index}}: {{$value}}</li>
      {{/each}}
      <!-- Traversal expression object -->
      <p>Traversal expression object</p>
      {{each objList as value index}}
      <li>{{index}}: {{value}}</li>
      {{/each}}
      <!-- $Abbreviation -->
      <p>$Abbreviation</p>
      {{each objList}}
      <li>{{$index}}: {{$value}}</li>
      {{/each}}

      <!-- The template contains child templates,expression -->
      {{include 'news_list'}}

      <!-- Auxiliary method -->
    </div>
  </script>

  <script id="news_list" type="text/html">
    <p>The template contains child templates,expression</p>
    <ul>
      {{each list as value i}}
      <li>Indexes {{i + 1}} : {{value + 1}}</li>
      {{/each}}
    </ul>
  </script>

  <script>
    const data = {
      name: 'zhangsan',
      value: '<h1>lisi</h1>',
      num: 0,
      bool: true,
      list: [1, 2, 3, 4, 5],
      objList: {
        name: 'zhangsan',
        age: '18',
        addr: 'Guangdong'
      }
    }
    let temp = template('test', data)
    document.getElementById('content').innerHTML = temp
  </script>
</body>

</html>

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nkzqrjai-1626757481472) (/ eised / javascript_notes / raw / Master / readme. Assets / image-20200126152808449. PNG)]

<!DOCTYPE HTML> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>no escape-demo</title> 
<script src="../dist/template.js"></script> 
</head> 
  
<body> 
 <h1>No escape HTML</h1> 
 <div id="content"></div> 
 <script id="test" type="text/html"> 
 <p>No escape:{{#value}}</p> 
 <p>Default Escape: {{value}}</p> 
 </script> 
  
 <script> 
 var data = { 
  value: '<span style="color:#F00">hello world!</span>' 
 }; 
 var html = template('test', data); 
 document.getElementById('content').innerHTML = html; 
 </script> 
</body> 
</html> 

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ln8veyom-1626757481474) (/ eised / javascript_notes / raw / Master / readme. Assets / image-20200126152827260. PNG)]

<!DOCTYPE HTML> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>include-demo</title> 
<script src="../dist/template.js"></script> 
</head> 
  
<body> 
<div id="content"></div> 
<script id="test" type="text/html"> 
<h1>{{title}}</h1> 
{{include 'list'}} 
</script> 
<script id="list" type="text/html"> 
<ul> 
 {{each list as value i}} 
  <li>Indexes {{i + 1}} : {{value}}</li> 
 {{/each}} 
</ul> 
</script> 
  
<script> 
var data = { 
 title: 'Embedded sub template', 
 list: ['literature', 'Blog', 'Photography', 'film', 'ballad', 'travel', 'guitar'] 
}; 
var html = template('test', data); 
document.getElementById('content').innerHTML = html; 
</script> 
</body> 
</html> 

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-abz6hnam-1626757481475) (/ published / javascript_notes / raw / Master / readme. Assets / image-20200126152842459. PNG)]

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-7kusclf2-1626757481476) (/ published / javascript_notes / raw / Master / readme. Assets / image-20200126152920878. PNG)]

Classification of expressions and operators

The left toolbar is an alphabetical list.

Main expression

Basic keywords and common expressions in JavaScript.

  • this

    this keyword points to the execution context of the function.

  • function

    The function keyword defines a function expression.

  • class

    The class keyword defines a class expression.

  • function*

    The function * keyword defines a generator function expression.

  • yield

    Pause and resume the generator function.

  • yield*

    Delegate to another generator function or iteratable object.

  • async function

    async function defines an asynchronous function expression.

  • await

    Pause or resume the execution of asynchronous functions and wait for the resolve/reject callback of promise.

  • [\]

    Array initialization / literal syntax.

  • {}

    Object initialization / literal syntax.

  • /ab+c/i

    Regular expression literal syntax.

  • ( )

    Grouping operators.

Left expression

The value on the left is the target of the assignment.

  • Property accessor

    Member operators provide access to properties or methods of objects (object.property and object["property"])

  • new

    The new operator creates a constructor instance.

  • new.target

    In the constructor, new Target pointing new Constructor called.

  • super

    super keyword calls the constructor of the parent class

  • ...obj

    The expansion operator can expand an iteratable object into multiple parameters at the position of the function call, or expand it into multiple array elements in the array literal.

Self increasing and self decreasing

Pre / post self increasing operator and pre / post self decreasing operator

  • A++

    Post increment operator

  • A--

    Post subtraction operator

  • ++A

    Prefix autoincrement operator

  • --A

    Leading subtraction operator

Unary operator

Unary operators have only one operand

  • delete

    The delete operator is used to delete the properties of an object

  • void

    The void operator indicates that the expression discards the return value

  • typeof

    The typeof operator is used to determine the type of a given object

  • +

    The unary addition operator converts the operation to type Number

  • -

    The unary subtraction operator converts the operation to type Number and negates it

  • ~

    Bitwise non operator

  • !

    Logical non operator

Arithmetic operator

An arithmetic operator takes two values (literal or variable) as operands and returns a single value.

  • +

    Addition operator

  • -

    Subtraction operator

  • /

    Division operator

  • *

    Multiplication operator

  • %

    Modulo operator

Relational operator

The comparison operator compares two operands and returns a Boolean value based on the comparison result.

  • in

    The in operator is used to determine whether an object has a given property

  • instanceof

    The instanceof operator determines whether an object is an instance of another object

  • <

    Less than operator

  • >

    Greater than operator

  • <=

    Less than or equal to operator

  • >=

    Greater than or equal to operator.

Note: = > is not an operator, but Arrow function The identifier of the.

Equality operator

If equal, the operator returns true of boolean type, otherwise false.

  • ==

    Equality operator

  • !=

    Inequality operator

  • ===

    Congruent operator

  • !==

    Non congruent operator

Shift Bitwise Operators

Move numbers on a binary basis

  • <<

    Bitwise left shift operator.

  • >>

    Bitwise shift right operator.

  • >>>

    Bitwise unsigned right shift operator.

Binary bit operator

Binary operators take their operands as a set of 32 binary bits (0 or 1) and return standard JavaScript values.

  • &

    Binary AND (AND).

  • |

    Binary OR (OR).

  • ^

    Binary exclusive or (XOR).

binary operation

Logical operators are typically used for boolean (logical) value operations, which return boolean values.

  • &&

    Logic and

  • ||

    Logical or

Conditional (ternary) operator

Assignment Operators

The assignment element character assigns the value of the right operand to the left operand and modifies its value to a value equal to the right operand.

  • =

    Assignment operator.

  • *=

    Assignment product.

  • /=

    Assignment quotient.

  • %=

    Assignment and remainder.

  • +=

    Assignment sum.

  • -=

    Assignment and difference.

  • <<=

    Left displacement.

  • >>=

    Right displacement.

  • >>>=

    Unsigned right displacement.

  • &=

    Assignment and.

  • ^=

    Assignment is bitwise exclusive or.

  • |=

    Assign or.

  • [a, b\] = [1, 2\] {a, b} = {a:1, b:2}

    Deconstruction assignment allows you to assign attributes to arrays or object variables, which look similar to array and object literals by using the specified syntax.

  • comma operator

  • ,

    The comma operator allows multiple expressions to operate in a judgment state and finally returns the value of the last expression.

JavaScript operator priority value

valueoperatordescribeexample
20( )Expression grouping(3 + 4)
19.memberperson.name
19[]memberperson["name"]
19()function callmyFunction()
19newestablishnew Date()
17++Suffix incrementi++
17Suffix decrementi–
16++Prefix increment++i
16Prefix decrement–i
16!Logical no!(x==y)
16typeoftypetypeof x
15**Exponentiation (ES7)10 ** 2
14*ride10 * 5
14/except10 / 5
14%modulo division 10 % 5
13+plus10 + 5
13-reduce10 - 5
12<<Left displacementx << 2
12>>Right displacementx >> 2
12>>>Right displacement (unsigned)x >>> 2
11<less thanx < y
11<=Less than or equal tox <= y
11>greater thanx > y
11>=Greater than or equal tox >= y
11inProperties in object"PI" in Math
11instanceofObjectinstanceof Array
10==equalx == y
10===Strict equalityx === y
10!=Unequalx != y
10!==Strict inequalityx !== y
9&Bitwise ANDx & y
8^Bitwise XORx ^ y
7|Bitwise ORx | y
6&&Logic andx && y
5||Logical nox || y
4? :condition? "Yes" : "No"
3=assignmentx = y
3+=assignmentx += y
3-=assignmentx -= y
3*=assignmentx *= y
3%=assignmentx %= y
3<<=assignmentx <<= y
3>>=assignmentx >>= y
3>>>=assignmentx >>>= y
3&=assignmentx &= y
3^=assignmentx ^= y
3|=assignmentx |= y
2yieldPause functionyield x
1,comma7 , 8

**Note: * * light red indicates experimental or suggested Technology (ECMAScript 2016 or ES7)

g/zh-CN/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT)

Logical non operator

Arithmetic operator

An arithmetic operator takes two values (literal or variable) as operands and returns a single value.

  • +

    Addition operator

  • -

    Subtraction operator

  • /

    Division operator

  • *

    Multiplication operator

  • %

    Modulo operator

Relational operator

The comparison operator compares two operands and returns a Boolean value based on the comparison result.

  • in

    The in operator is used to determine whether an object has a given property

  • instanceof

    The instanceof operator determines whether an object is an instance of another object

  • <

    Less than operator

  • >

    Greater than operator

  • <=

    Less than or equal to operator

  • >=

    Greater than or equal to operator.

Note: = > is not an operator, but Arrow function The identifier of the.

Equality operator

If equal, the operator returns true of boolean type, otherwise false.

  • ==

    Equality operator

  • !=

    Inequality operator

  • ===

    Congruent operator

  • !==

    Non congruent operator

Shift Bitwise Operators

Move numbers on a binary basis

  • <<

    Bitwise left shift operator.

  • >>

    Bitwise shift right operator.

  • >>>

    Bitwise unsigned right shift operator.

Binary bit operator

Binary operators take their operands as a set of 32 binary bits (0 or 1) and return standard JavaScript values.

  • &

    Binary AND (AND).

  • |

    Binary OR (OR).

  • ^

    Binary exclusive or (XOR).

binary operation

Logical operators are typically used for boolean (logical) value operations, which return boolean values.

  • &&

    Logic and

  • ||

    Logical or

Conditional (ternary) operator

Assignment Operators

The assignment element character assigns the value of the right operand to the left operand and modifies its value to a value equal to the right operand.

  • =

    Assignment operator.

  • *=

    Assignment product.

  • /=

    Assignment quotient.

  • %=

    Assignment and remainder.

  • +=

    Assignment sum.

  • -=

    Assignment and difference.

  • <<=

    Left displacement.

  • >>=

    Right displacement.

  • >>>=

    Unsigned right displacement.

  • &=

    Assignment and.

  • ^=

    Assignment is bitwise exclusive or.

  • |=

    Assign or.

  • [a, b\] = [1, 2\] {a, b} = {a:1, b:2}

    Deconstruction assignment allows you to assign attributes to arrays or object variables, which look similar to array and object literals by using the specified syntax.

  • comma operator

  • ,

    The comma operator allows multiple expressions to operate in a judgment state and finally returns the value of the last expression.

JavaScript operator priority value

valueoperatordescribeexample
20( )Expression grouping(3 + 4)
19.memberperson.name
19[]memberperson["name"]
19()function callmyFunction()
19newestablishnew Date()
17++Suffix incrementi++
17Suffix decrementi–
16++Prefix increment++i
16Prefix decrement–i
16!Logical no!(x==y)
16typeoftypetypeof x
15**Exponentiation (ES7)10 ** 2
14*ride10 * 5
14/except10 / 5
14%modulo division 10 % 5
13+plus10 + 5
13-reduce10 - 5
12<<Left displacementx << 2
12>>Right displacementx >> 2
12>>>Right displacement (unsigned)x >>> 2
11<less thanx < y
11<=Less than or equal tox <= y
11>greater thanx > y
11>=Greater than or equal tox >= y
11inProperties in object"PI" in Math
11instanceofObjectinstanceof Array
10==equalx == y
10===Strict equalityx === y
10!=Unequalx != y
10!==Strict inequalityx !== y
9&Bitwise ANDx & y
8^Bitwise XORx ^ y
7|Bitwise ORx | y
6&&Logic andx && y
5||Logical nox || y
4? :condition? "Yes" : "No"
3=assignmentx = y
3+=assignmentx += y
3-=assignmentx -= y
3*=assignmentx *= y
3%=assignmentx %= y
3<<=assignmentx <<= y
3>>=assignmentx >>= y
3>>>=assignmentx >>>= y
3&=assignmentx &= y
3^=assignmentx ^= y
3|=assignmentx |= y
2yieldPause functionyield x
1,comma7 , 8

**Note: * * light red indicates experimental or suggested Technology (ECMAScript 2016 or ES7)

**Tip: * * the expression in parentheses will be fully evaluated before the value is used in the rest of the expression.

Keywords: Front-end

Added by lettie_dude on Sun, 16 Jan 2022 06:37:08 +0200