The API HTM5

New method of operation

1. Method of getting elements

Gets a single element, and the argument can be any selector we want.

document.querySelect('selector');
Copy the code

Gets multiple elements with an arbitrary selector

document.querySelectAll('selector');
Copy the code
2. Class operations

Add the class

oDiv.classList.add('the name of the class');
Copy the code

Remove the class

oDiv.classList.remove('the name of the class');
Copy the code

Detection of class

oDiv.classList.contains('the name of the class');
Copy the code

Switch the class

oDiv.classList.toggle('the name of the class');// If yes, delete; if no, add
Copy the code
3. Customize attributes

We can add custom attribute names to elements using data-custom attribute names. Once the addition is complete. Custom properties can be obtained and set using JS.

For example, define a data-test attribute name

Gets the custom property name

oDiv.dataset.test
Copy the code

Set custom properties

Odiv.dataset. Custom attribute name = valueCopy the code

File to read

To read a file, you must first upload the file, which can be achieved through the form control whose input type is File

<input type='file' name=' '>
Copy the code

Second, read the file through FileReader. After reading the file, the result is stored in the Result property instead of being returned directly

Common methods of FileReader
1.ReadAsBinaryString: Reads the file as binary code2.ReadAsDataURL: Reads the file as DataURL3.ReadAsText: Reads a file as textCopy the code
FileReader provides events
1.Onabort Is triggered when the file is read2.Onerror Is triggered when there is an error reading a file3.Onload is triggered when the read file is complete and only when the read is successful4.Onloadend is triggered when reading the file is complete, whether the reading succeeds or fails5.Onloadstart triggered when reading the file starts6.Onprogress is reading the fileCopy the code
Read file instance
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>read file</title>
</head>
<body>
    <input type="file" name="">
    <script type="text/javascript">
    var input = document.querySelector("input");
    input.onchange = function() {
        // Get the file
        var file = this.files[0];
        // Create a reader
        var reader = new FileReader();
        // Start reading
        reader.readAsText(file);
        // After the file is read, get the read result
        reader.onload = function() {
            console.log(reader.result); }}</script>
</body>
</html>
Copy the code

Obtaining network Status

Window.navigator. onlione returns the network status of the browser. Returns true when connected, false when disconnected.

The sample code

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>network status</title>
</head>
<body>
    <script type="text/javascript">
    // Get the current network status
    var state = window.navigator.onLine;
    if (state) {
        alert("Networking status");
    }
    else {
        alert("Off network state");
    }
    </script>
</body>
</html>
Copy the code

Geographic location

The Geolocation API allows users to provide their location to web applications. For privacy reasons, users will be asked for permission before reporting their location

Geolocation object

The geolocation API is provided through navigator.geolocation

if(navigator.geolocation){
    /* Location services available */    
}else{
    /* Location-based services are not available */
}
Copy the code
Get current location
if(navigator.geolocation){
    /* Location services available */
    navigator.geolocation.getCurrentPosition(function(postion){
        position.coords.latitude;/ / longitude
        position.coords.longitude;/ / latitude})}else{
    /* Location-based services are not available */
}
Copy the code

According to my recent test, the current native method of obtaining longitude and weft degree has not worked. After repeated tests, I guess the problem may be caused by the restrictions on browser positioning in China.

Baidu Map Location

So, in order to achieve positioning, we’d better use a third party. Such as Baidu map development platform, really!! You can have anything you want on this platform.

<! DOCTYPEhtml>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="Initial - scale = 1.0, the user - the scalable = no" />
    <style type="text/css">
    body.html.#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:Microsoft Yahei; }</style>
    <script type="text/javascript" src="Http://api.map.baidu.com/api?v=2.0&ak= your key"></script>
    <title>The map shows</title>
</head>
<body>
    <div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
    // Baidu Map API function
    var map = new BMap.Map("allmap");    // Create a Map instance
    map.centerAndZoom(new BMap.Point(116.404.39.915), 11);  // Initialize the map, set the center point coordinates and map level
    // Add a map type control
    map.addControl(new BMap.MapTypeControl({
        mapTypes:[
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
        ]}));      
    map.setCurrentCity("Beijing");          // Set the city displayed on the map must be set
    map.enableScrollWheelZoom(true);     // Enable mouse wheel zooming
</script>
Copy the code

Effect display:

Note: Be sure to apply for your own key.

Once you’re done registering for the site, go here to request a key

There are a number of Web service apis available here

Baidu Map Web service API provides HTTP/HTTPS interface for developers, that is, developers initiate retrieval requests in HTTP/HTTPS form and obtain retrieval data returned in JSON or XML format. Users can develop JavaScript, C#, C++, Java and other languages based on this map application.

However, the following services are all interfaces. We are not currently learning Ajax techniques. You can look at this technology. Very important. We can use these services after we learn Ajax techniques.

The local store

HTML5 Web storage, a better local storage than cookies.

With the rapid development of the Internet, web-based applications are becoming more and more common, but also more and more complex. In order to meet various needs, a large amount of data is often stored locally. In the traditional way, document. Cookie is used for storage, but its storage size is only about 4K, and parsing is quite complex, which brings a lot of inconvenience to development. Use sessionStorage and localStorage to store data

localStorage

Features:

  1. Permanent storage
  2. Multi-window sharing
  3. The capacity is about 20 MB
Commonly used method
window.localStorage.setItem(key,value); // Set the contents to be stored
window.localStorage.getItem(key); // Get the content
window.localStorage.removeItem(key);// Delete the content
window.localStorage.clear(); // Clear the content
Copy the code
sessionStorage
  1. The lifecycle is to close the current browser window
  2. It can be accessed in the same window
  3. The data size is about 5M
window.sessionStorage.setItem(key,value); // Set the contents to be stored
window.sessionStorage.getItem(key); // Get the content
window.sessionStorage.removeItem(key);// Delete the content
Copy the code

Audio audio

HTML5 provides a standard for playing audio files. Until now, there was no standard for playing audio on a web page. Today, most audio is played through plug-ins such as Flash. However, not all browsers have the same plug-ins.

Audio audio
The basic use
<audio controls="controls">
    <source src="my.mp3"  type="audio/mp3">Your browser does not support the audio element</audio>
Copy the code

  • Controls property to add audio controls, play, pause, and volume controls
  • Autoplay: Enables audio toplay automatically
  • Loop: Automatically repeats the audio

Inserts unsupported prompt text between
. The Audio element allows you to use multiple source tags that link to different audio files, and the browser will use the first supported audio file.

Browser support

Currently, this TAB supports three audio and video formats: MP3/Wav and Ogg;

The browser MP3 Wav Ogg
Internet Explorer 9+ YES NO NO
Chrome 6+ YES YES YES
Firefox 3.6 + YES YES YES
Safari 5+ YES YES NO
Opera 10+ YES YES YES

Similarly, Audio can work with JS to implement its own music player

Refer to the MDNvideo and Audio tags for related events: media object related events,DOM related events

Pure JS to achieve classical music player
<! DOCTYPEhtml>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Music player</title>
    <link type="text/css" href="css/style.css" rel="stylesheet" />
  </head>
  <body>
    <div class="btns-bg">
      <div class="PlayEy"></div>
      <div class="Btn"></div>
      <div class="Play">
        <audio id="audios" src="http://music.163.com/song/media/outer/url?id=504924216.mp3"></audio>
      </div>
    </div>
    <script type="text/javascript" src="js/script.js"></script>
  </body>
</html>
Copy the code

style.css

body {
  margin:0;
  background-repeat:no-repeat;
  background-position:50%;
  background-image:url(../img/page-bg.png);
  background-size:100% auto;
  background-color:#efebcb
}
.PlayEy {
  display:flex;
  justify-content:center;
  align-items:center;
  width:653px;
  height:653px;
  background:url(../img/bg_circle.png), url(../img/bg_center.png) no-repeat center;
  background-size:100% % auto
}
.Btn {
  position:absolute;
  display:flex;
  justify-content:center;
  align-items:center;
  width:95px;
  height:95px;
  background-color:#ff0;
  background:url(../img/btn-bg.png) no-repeat;
  animation:Btn-bg 3s linear infinite
}
.Play {
  position:absolute;
  width:29px;
  height:36px;
  background:red;
  background:url(../img/pause.png) no-repeat;
  transition:.5s
}
.btns-bg {
  display:flex;
  justify-content:center;
  align-items:center;
  margin:30px auto;
  width:653px;
  height:653px
}
@keyframes Btn-bg {
  from{}to {
    transform:rotate(360deg)}}Copy the code

script.js

var i = 0;
var oPlayEy = document.getElementsByClassName("PlayEy") [0];
var oPlay = document.getElementsByClassName("Play") [0];
var audios = document.getElementById('audios');
oPlay.onclick = function () {
    var seii = setInterval(function () {
        (i == 360)? i =0: i++;
        oPlayEy.style.transform = "rotate(" + i + "deg)";
        if (audios.paused) {
            clearInterval(seii)
        }
    }, 30);
    if (audios.paused) {
        audios.play();
        oPlay.style.backgroundImage = "url(img/play.png)";
        oPlay.style.width = 32 + "px";
        oPlay.style.height = 32 + "px";
    } else {
        audios.pause();
        oPlay.style.backgroundImage = "url(img/pause.png)";
        oPlay.style.width = 29 + "px";
        oPlay.style.height = 36 + "px"; }}Copy the code

Video video

The basic use
<video width="800" height="" controls=""> <source src="Hero.mp4" type="video/mp4"></source> <source src="Hero.ogv" Type ="video/ogg"></source> <source SRC =" hero.webm "type="video/webm">Copy the code

The Video element provides play, pause, and volume controls to control the video.

The

The content inserted between the video and tags is intended for display by browsers that do not support the video element.

The

Browser support
The browser MP4 WebM Ogg
Internet Explorer YES NO NO
Chrome YES YES YES
Firefox YES YES YES
Safari YES NO NO
Opera YES (from Opera 25) YES YES
Simple video DOM manipulation
<! DOCTYPEhtml>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div class="box">
      <button id="playOrStop">Play/Pause</button>
    </div>
    <video width="800" height="">
      <source src="Hero.mp4" type="video/mp4"></source>
    <source src="Hero.ogv" type="video/ogg"></source>
  <source src="Hero.webm" type="video/webm"></source>The current browser does not support video playback</video>
<script type="text/javascript">
  var playOrStop  = document.getElementById('playOrStop');
  var video  = document.querySelector('video');
  console.dir(video);
  console.dir(playOrStop);
  playOrStop.onclick = function(){
    console.log(video.paused);
    if(video.paused){
      video.play();
    }else{ video.pause(); }}</script>
</body>
</html>
Copy the code

The HTML5 implementation calls the camera

To call the camera, html5’s getUserMedia()API is used

The code is as follows:

<! DOCTYPEhtml>
<html lang="zh">
  <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></title>
  </head>
  <body>
    <video id="video" autoplay style="width: 480px; height: 320px;"></video>
    <div>
      <button id="capture">Taking pictures</button>
    </div>
    <! -- Show the photos taken -->
    <canvas id="canvas" width="480" height="320"></canvas>
    <script type="text/javascript">
      window.onload = function() {
        // 1. Obtain the label
        var video = document.getElementById('video');
        var capture = document.getElementById('capture');
        var ctx = document.getElementById('canvas').getContext('2d');
        // Call the media object
        // The argument is video or audio
        navigator.mediaDevices.getUserMedia({
          video: {
            width: 480.height: 320
          }
        }).then(function(stream) {
          // Get the window.URL object
          var URL = window.URL || window.webkitURL;
          // Create a video URL string
          try {
            video.src = URL.createObjectURL(stream);
          } catch (e) {
            video.srcObject = stream;
          }
          // Video playback
          video.play();
        }).catch(function(err) {
          console.log(err);
        })
        // Click the photo button event
        capture.onclick = function() {
          ctx.drawImage(video,0.0.480.320); }}</script>
  </body>
</html>
Copy the code