Web APIs – M-side events, JS plug-ins

1. M-side incident

The mobile version also has its own unique features. For example, the touch screen event touch (also called touch event) is available on both Android and IOS.

  • The touch screen event touch (also called touch event) is available in both Android and IOS.
  • The touch object represents a touch point. The touch point may be a finger or a touch pen. Touch screen events respond to user finger (or stylus) operations on the screen or trackpad.
  • Common touch screen events are as follows:

td>

Touch screen touch event Description
touchstart Triggered when the phone touches a DOM element
touchmove Triggered when the finger slides on a DOM element
touchend Triggered when the finger is removed from a DOM element
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            background-color: blueviolet;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        // To be effective only on mobile terminal
        const div = document.querySelector('div')
        // 1. Touch
        div.addEventListener('touchstart',function () {
            console.log('Started')
        })
        // 2. Leave
        div.addEventListener('touchend',function () {
            console.log('left')
        })
        // 3. Move
        div.addEventListener('touchmove',function () {
            console.log('Keeping moving inside')
        })
    </script>
</body>
</html>

2. JS plug-in

Plug-in: It is some code written by others. We only need to copy the corresponding code to directly achieve the corresponding effect.

The basic process of learning plug-ins:

  • Familiarize yourself with the official website and understand what needs this plug-in can fulfill https://www.swiper.com.cn/
  • Watch online demos and find the demo that meets your needs https://www.swiper.com.cn/demo/index.html
  • View the basic usage process https://www.swiper.com.cn/usage/index.html
  • Check the API documentation to configure your own plug-in https://www.swiper.com.cn/api/index.html
  • Note: When multiple swipers are used at the same time, the class names need to be distinguished.

Enter the URL https://www.swiper.com.cn/, then click to get Swiper and download Swiper.

It can also be used by selecting the Chinese tutorial

You can see below are the compressed packages of different versions of swiper. If you want to download the one, just click on it.

For versions below 6.8.4, you can find the css and js files here. For other versions, you can find the ones with the suffix css and js. Just copy them directly to the required project

If you want to know how to use it, you can check the documentation, enter Swiper, click on the online demonstration, select the corresponding demonstration tutorial, and then choose what you need. I chose the basic demonstration and the paginator (030).

When there is an Internet connection, you can directly click on the new window to open, you can directly right-click to view the source code, and then copy and paste.

If there is no Internet connection, you can directly enter the compressed package you just downloaded, find the demos document, and find the html file sorted as 030.

You can find that this cannot play by itself. You can check the API documentation. What we need now is for it to switch automatically. You can find Auto play (automatic switching)

Use delay here to let it play once a second

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel = "stylesheet" href = "./css/swiper.min.css">
    <style>
        .box {
            position: relative;
            width: 800px;
            height: 300px;
            background-color: blueviolet;
            margin: 100px auto;
        }
        html,
        body {
            position: relative;
            height: 100%;
        }

        body {
            background: #eee;
            font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
            font-size: 14px;
            color: #000;
            margin: 0;
            padding: 0;
        }

        .swiper {
            overflow: hidden;
            width: 100%;
            height: 100%;
        }

        .swiper-slide {
            text-align: center;
            font-size: 18px;
            background: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .swiper-slide img {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="swiper mySwiper">
            <div class="swiper-wrapper">
              <div class="swiper-slide">Slide 1</div>
              <div class="swiper-slide">Slide 2</div>
              <div class="swiper-slide">Slide 3</div>
              <div class="swiper-slide">Slide 4</div>
              <div class="swiper-slide">Slide 5</div>
              <div class="swiper-slide">Slide 6</div>
              <div class="swiper-slide">Slide 7</div>
              <div class="swiper-slide">Slide 8</div>
              <div class="swiper-slide">Slide 9</div>
            </div>
            <div class="swiper-pagination"></div>
          </div>
        
    </div>
    <script src = "./js/swiper.min.js"></script>
    <script>
        var swiper = new Swiper(".mySwiper", {
            // small dots
            pagination: {
                el: ".swiper-pagination",
            },
            // Autoplay
            autoplay: {
                delay: 1000,//Switch once every second
                disableOnInteraction: false, //After mouse click and touch, playback will continue automatically
            },
            // Can be controlled by keyboard
            keyboard: {
                enabled: true,
                onlyInViewport: true,
            },
        });
    </script>
</body>
</html>

3. Student information form case

Business module:

①: Click the input button to enter data

②: Click Delete to delete the current data

illustrate:

Minimize dom operations and take the form of operating data

Adding and deleting are operations on arrays, and then the page is rendered based on the array data.

Core idea

①: Declare an empty array

②: Click to enter, generate objects based on relevant data, and append them to the array.

(1). First cancel the default submission event of the form

(2). Create a new object, which stores the data obtained from the form. The format is as shown on the right.

(3). Append to array

(4). Rendering data. Traverse the array, dynamically generate tr, fill in the corresponding td data, and append it to tbody

(5). Reset form

(6). Pay attention to prevent multiple pieces of data from being generated multiple times. Clear the tbody first.

③: Render the page based on the array data – the rows of the table

④: Click the delete button to delete the data in the corresponding array.

(1). Use event delegation to register click events for tbody

(2). Click the link. What you want to delete is the data in the corresponding array, not the DOM node. How to find this data?

(3). When rendering data earlier, dynamically add the custom attribute data-id=”0″ to a link, so that you can know the index number by clicking on the current object.

(4). Use splice to delete this data based on the index number.

(5). Re-render

⑤: Click to add a form that requires verification

(1). Get all the forms that need to be filled in. They all have the name attribute in common.

(2). Traverse these forms. If a value is empty, return and prompt the input to be empty to interrupt the program.

(3). Pay attention to the writing position. It should be placed in front of the new data and behind the blocking default behavior.

index.css

* {
  margin: 0;
  padding: 0;
}

a {
  text-decoration: none;
  color:#721c24;
}
h1 {
  text-align: center;
  color:#333;
  margin: 20px 0;
 
}
table {
  margin:0 auto;
  width: 800px;
  border-collapse: collapse;
  color:#004085;
}
th {
  padding: 10px;
  background: #cfe5ff;
  
  font-size: 20px;
  font-weight: 400;
}
td,th {
  border:1px solid #b8daff;
}
td{
  padding:10px;
  color:#666;
  text-align: center;
  font-size: 16px;
}
tbody tr {
  background: #fff;
}
tbody tr:hover {
  background: #e1ecf8;
}
.info {
  width: 900px;
  margin: 50px auto;
  text-align: center;
}
.info input, .info select {
  width: 80px;
  height: 27px;
  outline: none;
  border-radius: 5px;
  border:1px solid #b8daff;
  padding-left: 5px;
  box-sizing: border-box;
  margin-right: 15px;
}
.info button {
  width: 60px;
  height: 27px;
  background-color: #004085;
  outline: none;
  border: 0;
  color: #fff;
  cursor: pointer;
  border-radius: 5px;
}
.info .age {
  width: 50px;
}

Student information form case.html

<!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>Student Information Management</title>
  <link rel="stylesheet" href="css/index.css" />
</head>

<body>
  <h1>Add new students</h1>
  <form class="info" autocomplete="off">
    Name: <input type="text" class="uname" name="uname" />
    Age: <input type="text" class="age" name="age" />
    gender:
    <select name="gender" class="gender">
      <option value="Male">Male</option>
      <option value="Female">Female</option>
    </select>
    Salary: <input type="text" class="salary" name="salary" />
    Employment city: <select name="city" class="city">
      <option value="Beijing">Beijing</option>
      <option value="Shanghai">Shanghai</option>
      <option value="Guangzhou">Guangzhou</option>
      <option value="Shenzhen">Shenzhen</option>
      <option value="Cao County">Cao County</option>
    </select>
    <button class="add">Enter</button>
  </form>

  <h1>Employment List</h1>
  <table>
    <thead>
      <tr>
        <th>Student ID number</th>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Salary</th>
        <th>Employment City</th>
        <th>Operation</th>
      </tr>
    </thead>
    <tbody>
      <!--
        <tr>
          <td>1001</td>
          <td>Ouyang Batian</td>
          <td>19</td>
          <td>Male</td>
          <td>15000</td>
          <td>Shanghai</td>
          <td>
            <a href="javascript:">Delete</a>
          </td>
        </tr>
        -->
    </tbody>
  </table>
  <script>
    // Get elements
    const uname = document.querySelector('.uname')
    const age = document.querySelector('.age')
    const gender = document.querySelector('.gender')
    const salary = document.querySelector('.salary')
    const city = document.querySelector('.city')
    const tbody = document.querySelector('tbody')
    // Get all elements with name attribute
    const items = document.querySelectorAll('[name]')
    // Declare an empty array. Addition and deletion are operations on this array.
    const arr = []

    // 1. Input module
    // 1.1 Form submission event
    const info = document.querySelector('.info')
    info.addEventListener('submit', function (e) {
      // Prevent default behavior from jumping
      e.preventDefault()
      // console.log(11)

      // Form verification is performed here. If it fails, it will be interrupted directly without adding data.
      // First traverse the loop
      for (let i = 0; i < items.length; i + + ) {
        if (items[i].value === '') {
          return alert('The input content cannot be empty')
        }
      }
      //Create new object
      const obj = {
        stuId: arr.length + 1,
        uname: uname.value,
        age: age.value,
        gender: gender.value,
        salary: salary.value,
        city: city.value
      }
      // console.log(obj)
      //Append to the array
      arr.push(obj)
      // console.log(arr)
      //Clear form reset
      this.reset()
      // Call rendering function
      render()
    })


    // 2. Rendering function because both adding and deleting require rendering
    function render() {
      // First clear the previous rows of tbody and render the data in the latest array.
      tbody.innerHTML = ''
      // Traverse the arr array
      for (let i = 0; i < arr.length; i + + ) {
        // generate tr
        const tr = document.createElement('tr')
        tr.innerHTML = `
          <td>${arr[i].stuId}</td>
          <td>${arr[i].uname}</td>
          <td>${arr[i].age}</td>
          <td>${arr[i].gender}</td>
          <td>${arr[i].salary}</td>
          <td>${arr[i].city}</td>
          <td>
            <a href="javascript:" data-id=${i}>Delete</a>
          </td>
        `
        //Append element parent element.appendChild(child element)
        tbody.appendChild(tr)
      }
    }


    // 3. Delete operation
    // 3.1 Event delegate tbody
    tbody.addEventListener('click', function (e) {
      if (e.target.tagName === 'A') {
        // Get the custom attribute data-id of the current element
        // console.log(e.target.dataset.id)
        //Delete the corresponding data in the arr array
        arr.splice(e.target.dataset.id, 1)
        console.log(arr)
        // Render again
        render()
      }
    })
  </script>

</body>

</html>

4. Redrawing and reflow

4.1 How the browser renders the interface

  • Parse (Parser) HTML and produce DOM Tree (DOM Tree)
  • At the same time, parse (Parser) CSS and generate style rules (Style Rules)
  • Generate a rendering tree (Render Tree) based on the DOM tree and style rules
  • Carry out layout (Layout (reflow/rearrangement): obtain the geometric information (position, size) of the node based on the generated rendering tree
  • Painting (redrawing): Painting the entire page based on calculations and acquired information
  • Display: displayed on the page

4.2 Reflux (rearrangement)

When the size, structure, layout, etc. of some or all elements in the Render Tree change, the browser will re-render part or all of the document, a process called reflow.

4.3 Redraw

Since the change of the style of a node (element) does not affect its position in the document flow and document layout (such as color, background-color, outline, etc.), it is called redrawing.

Redrawing does not necessarily cause reflow, and reflowing always causes redrawing.

  • Operations that will cause reflow (reflow):
    • The first refresh of the page
    • The browser window size changes
    • The size or position of the element changes
    • Change font size
    • Changes in content (such as: input in the input box, size of the picture)
    • Activate CSS pseudo-classes (eg: hover)
    • Script to manipulate DOM (add or remove visible DOM elements)

Simply understand that if it affects the layout, there will be reflow.