js advanced -h5 new features

New label

Represents a block Represents an article. Such as articles, comments, posts and blogs Represents a header Represents a footer Indicates navigation Represents the sidebar. Such as the sidebar of the article Indicates media content grouping (less used) Indicates the mark (less used) indicates the progress (less used) indicates the date (less used)

New form element

Email can only enter email format. Automatic verification function.

tel mobile number.

url can only enter url format.

number can only enter numbers [required]

Search search box

range slider

color pickup

Time time

Date date

datetime date

Month month

Week week

(2) web local cache

The web cache includes sessionstorage, localstorage and cookies

(1) Same point:

Cookies, sessionstorage and localstorage can all be used to store data on the browser side

(2) Differences:

1. Different storage sizes

cookie data shall not exceed 4KB local storage, and sessuibstorage shall be 5M

2. Different data validity periods

The cookie is valid for the set (server settings) validity period
localstorage is always valid and will not expire unless it is actively deleted
sessionstorage is valid before the browser is closed. It can be closed and destroyed
Note: localstorage can be understood as permanent storage, and sessionstorage is temporary storage
method:

Save data (setitem)
getItem() fetch data

(3) websocket

Function: the front-end and back-end can be connected all the time, which is convenient for us to interact with the front and back of the data

Use steps:

1. Initialize project

npm init -y

2. Installation dependency (and installation module)

npm i koa koa-websocket koa-static

3. Operation project

//Server side code app js

const Koa = require("koa");
const path = require("path");
const websockify = require("koa-websocket");
const app = websockify(new Koa());
const serv = require("koa-static");
app.use(serv(__dirname + "/public")); 

app.ws.use((ctx, next) => {
  // Send a message to the front end
  let count = 1;
  setInterval(() => {
    ctx.websocket.send(
        `${count++}. If you don't lie down and win,Then stand up and run`
    );
  }, 2000);

  // Monitor the information sent by the front end
  ctx.websocket.on("message", function (message) {
    console.log(message);
  });
});

app.listen(3000,()=>{
    console.log('http://localhost:3000');
})

//html side code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <script>
      // Create sock
        var ws = new WebSocket("ws://localhost:3000");
        ws.onopen = function (evt) {
            console.log("Connection successful");
            ws.send("I'm Zhang San");
        };
        // Monitor server information
        ws.onmessage = function (evt) {
            document.write("Receive the information from the server: " + evt.data+'<br/>');
        };

        ws.onclose = function (evt) {
            console.log("Connection closed.");
        };
    </script>
</body>
</html>

Audio and video

(1) Audio
html5 solves the problem of audio playback through tags

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <audio src="https://www.w3school.com.cn/i/horse.ogg" controls>
        no supper  <!-- Here is to let him display when our audio is incompatible -->
    </audio>
</body>
</html>

video

HTML5 solves the problem of video playback through tags.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <video src="https://www.w3school.com.cn/i/movie.ogg" controls autoplay>
       no supper  <!-- Display when video is incompatible -->
   </video>
</body>
</html>

Dom operation

(1). selector

document.queryselector()
document.queryselectorAll() gets a pseudo array of dom elements

(2) Custom properties
h5 you can add custom attributes
Syntax: Data XX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
  <div title="I am a title" data-time="1">I am a div</div>
  <script>
      var div=document.querySelector('div');
      //Gets the title attribute of the dom element
      console.log(div.title);
      //Get the value of our custom attribute
      console.log(div.dataset.time);
  </script>
</body>
</html>

Summary: what are the ways to store data?
1. Browser cache: cookie,sessionStorage,localStorage
2. Store in variable
3. Store in database
4. Store in label (through custom attribute)
Data storage: find out how to save data, how to get data, and how to modify data

Data storage to learn:
1.promise save data
2.vuex
3. Applet local cache

Applet drag

1. Set draggable = "true" for the element to be dragged
2. Target element
(1). Bind the dragover event to block the default behavior (it cannot be put by default)
(2). Bind the drop event and put the dragged and dropped elements into it

3. Binding and dragging related events
ondrag is triggered when an element or selected text is dragged.
ondragstart is triggered when the user starts dragging an element or selected text
Ondragendtriggered when the drag operation ends
ondrop is triggered when an element or selected text is released on a releasable target
ondragover is triggered when an element or selected text is dragged onto a releasable target

<!DOCTYPE html>
<html> 
<head>
  <style type="text/css">
    div {
      width: 198px;
      height: 66px;
      padding: 10px;
      border: 1px solid #aaaaaa;
    }
    
  </style>
</head>

<body>
  <p>Please put W3School Drag and drop your picture into the rectangle:</p>
  <div id="div" ondrop="test()" ondragover="dev()"> </div>
  <div id="div1" ondrop="test()" ondragover="dev()"> </div>
  <img draggable="true" src="https://www.w3school.com.cn/i/eg_dragdrop_w3school.gif" alt="">

  <script>
      function dev(){
          event.preventDefault();
      }
    function test(){
        var div=event.target;
        var img =document.querySelector('img');
        div.appendChild(img);
    }
  </script>
</body> 
</html>

Offline cache

In html5, we can easily build an offline (no network state), and only need to create a cachemanifest cache manifest file

(1). Offline cache advantage

1. Configure the resources to be cached
2. The application without network connection is still available;
3. Read cache resources locally to improve access speed and enhance user experience
4. Reduce requests and ease the burden on the server

(2) Cache manifest file

The cache manifest file lists the resources that the browser should cache for offline access. Recommended appcache is used as the suffix, and MIME type is also added.

How to write the contents in the cache list file:

(1) Write CACHE MANIFEST on the top line.

(2) CACHE: newline specifies the static resources we need to CACHE, such as css, image, js, etc.

(3) NETWORK: newline specifies the resources that need to be accessed online. Wildcards can be used (that is, resources that do not need to be cached and can only be accessed under the NETWORK).

(4) FALLBACK: line feed: an alternate resource when the cached file cannot be found (when a resource cannot be accessed, it will be automatically replaced by another resource).

##(3) Examples
(1) For example, we create a file called demo Appcache file as follows
demo.appcache

CACHE MANIFEST
# Notes to#start
#Here are the files to cache
CACHE:
    http://img.smyhvae.com/2016040101.jpg

(2) Add the attribute manifest = "demo.appcache" in the root element (html) of the page where the application needs to be cached. The path should be correct. For example:

<!DOCTYPE html>
<html manifest="demo.appcache">
  <head lang="en">
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <body>
    <img src="http://img.smyhvae.com/2016040101.jpg" alt="" />
  </body>
</html>

Maps and geolocation

Get geolocation:
1.html5 provides an api for obtaining location
2. You can use the public api submitted by Baidu map, Tencent map or Gaode map to complete map status and map drawing
Tencent statement is recommended

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Hello world!</title>
    <style type="text/css">
    #container{
        /*Map (container) display size*/
        width:1200px;
        height:400px;
    }
    </style>
    <!--introduce Javascript API GL,See the following for parameter description-->
    <script src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
    <script>
        //The map initialization function is named init in this example, which can be defined by the developer according to the actual situation
        function initMap() {
            //Define the coordinates of the map center point
            var center = new TMap.LatLng(28.160613,112.985095)
            //Define the map variable and call TMAP Map() constructor creates a map
            var map = new TMap.Map(document.getElementById('container'), {
                center: center,//Set the coordinates of the map center point
                zoom: 17.2,   //Set map zoom level
                pitch: 43.5,  //Set pitch angle
                rotation: 45    //Set map rotation angle
            });
        }
    </script>
</head>
<!-- After the page is loaded, call init function -->
<body onload="initMap()">
    <!-- Define map display container -->
    <div id="container"></div>
</body>
</html>

Drawing canvas

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="600"></canvas>
      
    <script>
      var c = document.getElementById("myCanvas");
      var cxt = c.getContext("2d"); //Get 2d drawing object
      cxt.moveTo(10, 10); //The starting point of the line
      cxt.lineTo(150, 50); //Draw a line
      cxt.lineTo(10, 50);
      cxt.stroke(); //Line
      cxt.fillStyle = "#FF0000 "; / / fill color
      cxt.beginPath(); //Start path
      cxt.arc(70, 18, 15, 0, Math.PI * 2, true); //Draw a circle
      cxt.closePath(); //End path
      cxt.fill(); //fill

      var img = document.createElement("img");
      img.src = "https://www.w3school.com.cn/i/eg_dragdrop_w3school.gif";
      img.onload = function () {
        cxt.drawImage(img, 200, 200); //Canvas fill picture
      };
    </script>
  </body>
</html>

Keywords: Javascript Front-end websocket

Added by IceHawk on Mon, 14 Feb 2022 14:07:14 +0200