HTML5

1.1 Basic concepts of HTML5

1.1.1 know HTML 5

  • HTML5Not a new language, but the fifth major revision of HTML
  • support: All major browsers (Chrome, Firefox, Safari), IE9 and above support HTML5, but IE8 and below do not
  • Changed the way users interact with documents: multimedia (video.audio.canvas)
  • Added other new features:Semantic features.Local Storage feature.Web multimedia.2 d 3 d, special effects,The transition.animation)
  • In contrast to HTML4, HTML5:
    • Discard some unreasonably uncommon tags and attributes and add some tags and attributes (forms)
    • From a code point of view, HTML5’s web structure code is much simpler.

1.1.2 Some rules established by HTML5

  • New features should be based on HTML, CSS, DOM, and JavaScript.

  • Reduce the need for external plug-ins (such as Flash)

  • Better error handling

  • More tags to replace scripts

  • HTML5 should be device independent

  • The development process should be transparent to the public

1.1.3 Some new features in HTML5

  • Canvas element for drawing

  • Video and audio elements for media playback

  • Better support for local offline storage

  • New special content elements such as article, footer, header, nav, section

  • New form controls such as Calendar, Date, Time, email, URL, and Search

1.2 Semantic Labels

1.2.1 Structured Labels

The label features
header Defines the document header area, typically used in the header
section Defines an area in the document instead of a div layout
nav Define the navigation bar
aside Define sidebars, ads, groups of nav elements, and other similar content sections. Aside content should be related to the content of an article. Generally irrelevant to the text.
footer Defines the content of the bottom area of the document, usually ending in footer
article The tag defines the external content. External content can be a new article from an external news provider or text from a forum.
figure Defines a single piece of content (image, icon, code, etc.), usually used to display an image and its description.
figure

Figure Caption Defines the title of a figure, and puts it first or last of its child elements.

<figure>
    <figcaption></figcaption>
    <img src="/">
</figure>
Copy the code

1.2.2 Special Structure Labels

ruby

Define comments, inline elements.

<ruby>dragon<rt>long</rt></ruby>
Copy the code

mark

Defines marked text for highlighting

meter

To define scalar measurements within a known range or score value, the tag should not be used to indicate progress (in the progress bar). If marking a progress bar, use the tag.

  • Min min

  • Max maximum

  • Low Indicates the lowest value

  • Optimum specifies the best value

  • High Indicates the maximum value

<meter min="0" max="10" value="3" low="5" optimum="9" high="9" ></meter>
Copy the code

progress

The TAB shows the progress of a task or process, which is usually used in combination with JS. When no value is given, it is a loaded state. In Google, it is a scrolling state, and in Firefox, it is a flash state. Width and height Settings are supported, but the background color needs to be combined with JS.

  • Max maximum
  • The value of the current value
<progress value="50" max="100"></progress>
Copy the code

details

Used to describe detailed sections of a document, similar to defining lists

<details>
    <summary>The title</summary>
    <p>A description of the title</p>
</details>
Copy the code

wbr

Defines where text is wrapped, the equivalent of inline word wrapping. A single tag

1.3 compatibility

  • Some HTML5 content is compatible with IE9, IE8 and below are not compatible with H5 at all, this type of browser is not considered in the following content. The latest versions of Safari, Chrome, Firefox, and Opera support some HTML5 features.

  • Some CSS3 shall be prefixed with compatibility:

    • – WebKit – Usually compatible with Chrome
    • – Moz – Often used with Firefox
    • -o- Often used to be compatible with Opera
    • -ms- Compatible with Internet Explorer
  • Compatibility check website: caniuse.com/

  • Compatibility treatment: the introduction of the third-party plug-in HTML5shiv.js

1.4 HTML5 smart forms

1.4.1 type type

Email mailbox

Verify that the email format is correct. If not, click the submit button to be prompted.

<input type="email" class="in1">Copy the code

Tel phone

Tel is not for verification, its essential purpose is to be able to open the numeric keypad on the mobile end. This means that the numeric keypad limits the user to only numbers

Input type="tel">Copy the code

The url address

Only valid web addresses can be entered for authentication: http:// must be included

Input type="url">Copy the code

The number of digital

Restrict input to numbers, no other characters (except decimal point)

  • Max: maximum
  • Min: the minimum value
  • Value: the default value
<input type="number">Copy the code

Search delete function

Humanized input experience. After you enter content in the form, a close symbol is displayed to delete the input

<input type="search">
Copy the code

range

Drag the bar, step property can set the size of each change, support value, Max, min and other properties. The default value is 50% of the maximum value

<input type="range" step="2" max="10" min="0" value="5">
Copy the code

Color palette

Click to bring up the palette.

<input type="color">
Copy the code

Time time

When a vehicle

<input type="time" class="in1">
Copy the code

The date date

Year, month, day

<input type="date">
Copy the code

Datetime Date and time

Most browsers don’t support it, only apple’s Safari browser

<input type="datetime">
Copy the code

Datetime-local Indicates the date and time

Date and time

<input type="datetime-local">
Copy the code

In the month

<input type="month">
Copy the code

Week week

<input type="week">
Copy the code

1.4.2 New attributes of the form

Placehoder prompts for text

<input type="text" placehoder="Please enter">
Copy the code

Autofocus Specifies the focus

<input type="text" autofocus>
Copy the code

autocomplete

The value can be on or off.

  • onTurn on autocomplete
  • offTurn off autocomplete

Conditions for automatic completion:

  • Previously entered content must be submitted
  • The current addautocompleteElement must havenameattribute
<input type="text" autocomplete="on">
Copy the code

Required Must be entered

You have to enter something in the input box

<input type="text" required>
Copy the code

pattern

Add regular expression validation

<input type="tel" pattern="^ (\ + 86)? 1/d{10}$">
Copy the code

multiple

Enables the File form to upload multiple files

It is also possible to enter multiple email addresses in an email, separated by commas

<input type="file" multiple>
<input type="email" multiple>
Copy the code

Form attribute

If you specify the form ID, the current form element’s data will also be submitted when the form with the specified ID submits data in the future.

<form action="http://www.baidu.com" id="from1">
	<input type="text">
</form>
<input type="text" form="from1">
Copy the code

1.4.3 New HTML elements

datalist

Text box enter the keyword to display the datalist ID value corresponding to the alternate option list attribute

Plain text box
Please specify your gender:<input type="text"  list="lis">
<datalist id="lis">
    <option value="English" label="Don't"></option>
    <option value="Front end" label="So simple"></option>
    <option value="Java" label="High number of users"></option>
</datalist>
Copy the code
The url
Web site:<input type="url" list="urls">
<datalist id="urls">
   <option value="http://www.baidu.com" label="Baidu">
   <option value="http://www.sohu.com" label="Baidu">
   <option value="http://www.163.com" label="Baidu">
</datalist>
Copy the code
  • Option can be single label or double label

  • Label is displayed after value

1.4.4 Added events in the Form

oninput

Listen for changes to the current specified content, whenever the content changes, will trigger this event (add content, remove content), will trigger this event.

The difference between onKeUp and OnKeUp: Each key lift is triggered once.

oInp.oninput = function () {
	// Content section...
}
Copy the code

oninvalid

An event that is triggered when validation fails, usually in conjunction with pattern validation in input.

<form action="http://www.baidu.com">Please enter your mobile phone number:<input type="text" pattern="^1\d{10}$">
	<button>submit</button>
</form>
Copy the code
var oInp = document.querySelector("input");
oInp.oninvalid = function () {
	/* Set the default prompt */
	this.setCustomValidity("Please enter eleven telephone numbers beginning with one!")}Copy the code

Where, setCustomValidity can set the default prompt information.

1.5 Audio and video

1.5.1 Get to know HTML5 video

Common video formats

  • Video components: picture, audio, coding format

  • Video coding: H.264, Theora, VP8(Google open source)

Common audio formats

  • Audio encoding: ACC, MP3, Vorbis

HTML5 supported video formats

  • Ogg= Ogg file with Theora video encoding +Vorbis audio encoding, supported browsers :F, C, O

  • MEPG4= MPEG4 file with H.264 video encoding +AAC audio encoding, supported browsers: S and C

  • WebM= WebM format with VP8 video encoding +Vorbis audio encoding, supported browsers: I, F, C, O

1.5.2 video element

attribute value describe
autoplay Autoplay (optionally without writing values) If this property is present, the video is played immediately after it is ready
controls controls If present, the control, such as a play button, is displayed to the user
loop loop If this property is present, playback starts again when the media file has finished playing
src src The URL to play the video
preload preload If this property is present, the video is loaded when the page loads and ready to play. If “autoplay” is used, this property is ignored
poster poster Wait for the image to play before the video plays
width px Set the width of the video to play
height px Set the video to play
<video src="mp4.mp4" controls width="400" poster="images/1.jpg"></video>
Copy the code

source

Because different browsers support different video formats, so when we add videos. Consider whether your browser supports it. We can prepare video files in multiple formats and let the browser choose automatically.

<video>
	<source src="flv.flv" type="video/flv">
	<source src="mp4.mp4" type="video/mp4">Your browser does not support video playback in this format</video>
Copy the code

API methods

methods describe
addTextTrack() Adds a new text track to audio/video
canPlayType() Checks whether the browser can play the specified audio/video type
load() Reload the audio/video elements
play() The audio/video starts to play
pause() Pause the currently playing audio/video
Exit full screen webkit document.webkitCancelFullScreen();

Firefox document.mozCancelFullScreen();

W3C document.exitFullscreen()
Full screen webkit element.webkitRequestFullScreen()

Firefox element.mozRequestFullScreen()
W3C element.requestFullscreen()

API properties

attribute describe
audioTracks Returns an AudioTrackList object representing available tracks
autoplay Sets or returns whether audio/video is played immediately after loading
buffered Returns the TimeRanges object representing the buffered portion of the audio/video
controller Returns the MediaController object representing the current MediaController for audio/video
controls Sets or returns whether to display audio/video controls (such as play/pause, etc.)
crossOrigin Sets or returns audio/video CORS Settings
currentSrc Returns the URL of the current audio/video
currentTime Sets or returns the current playing position in audio/video in seconds
defaultMuted Sets or returns whether audio/video is muted by default
defaultPlaybackRate Sets or returns the default playback speed of audio/video
duration Returns the length of current audio/video in seconds
ended Returns whether audio/video playback has ended
error Returns a MediaError object representing the audio/video error status
loop Sets or returns whether the audio/video should be replayed at the end
mediaGroup Sets or returns the group to which audio/video belongs (used to connect multiple audio/video elements)
muted Sets or returns whether audio/video is muted
networkState Returns the current network status of audio/video
paused Sets or returns whether audio/video is paused
playbackRate Sets or returns the speed of audio/video playback
played Returns the TimeRanges object that represents the played portion of the audio/video
preload Sets or returns whether audio/video should load after the page loads
readyState Returns the current ready state of the audio/video
seekable Returns the TimeRanges object representing the audio/video addressable portion
seeking Returns whether the user is searching in audio/video
src Sets or returns the current source of the audio/video element
startDate Returns a Date object representing the current time offset
textTracks Returns a TextTrackList object representing available text tracks
videoTracks Returns the VideoTrackList object representing the available video tracks
volume Sets or returns the volume of audio/video

The event

The event describe
abort When audio/video loading has been abandoned
canplay When the browser can play audio/video
canplaythrough When the browser can play without pausing for buffering
durationchange When the duration of the audio/video has changed
emptied When the current playlist is empty
ended When the current playlist has ended
error When an error occurs during audio/video loading
loadeddata When the browser has loaded the current frame of audio/video
loadedmetadata When the browser has loaded the audio/video metadata
loadstart When the browser starts looking for audio/video
pause When audio/video has been paused
play When audio/video has started or is no longer paused
playing When audio/video is ready after it has been paused or stopped for buffering
progress While the browser is downloading audio/video
ratechange When the playback speed of audio/video has been changed
seeked When the user has moved/jumped to a new location in the audio/video
seeking When the user starts to move/jump to a new location in the audio/video
stalled When the browser tries to get media data, but the data is not available
suspend When the browser deliberately does not fetch media data
timeupdate When the current playback position has been changed
volumechange When the volume has changed
waiting When the video stops due to the need to buffer the next frame

1.6 HTML5 action classes

  • classListA list of all styles for the current element
  • add()Add the class
  • remove()Delete the class
  • toggle()If you have it, remove it. If you don’t, add it
  • contains()If a class is included, return true if it is, false if it is not
  • item(n)Check the first of this itemnClass name, null if no
.add{ color: red; }
.remove{ color: green; }
.toggle{ color: purple; }
.contains{ color: yellow; }
Copy the code
<ul>
	<li>I'm the first Li</li>
	<li class="remove">I'm the second Li</li>
	<li class="toggle">I'm the third Li</li>
   <li class="toggle contains">I'm the fourth Li</li>
</ul>
Copy the code
var aLi = document.querySelectorAll("li");
aLi[0].onclick = function () {
	this.classList.add("add")
}
aLi[1].onclick = function () {
	this.classList.remove("remove")
}
aLi[2].onclick = function () {
	this.classList.toggle("toggle")
}
aLi[3].onclick = function () {
	this.classList.contains("contains")}console.log(aLi[3].classList.item(1))	//contains
Copy the code

1.7 Customizing Label Attributes

Definition specification:

  • data-Start, e.g. “data-name-xiaoyang”
  • data-There must be at least one string after multiple words are used-The connection
  • Names should always be in lower case and do not contain any uppercase characters
  • Don’t have any special symbols in the name
  • Do not use pure numbers in names
  • datasetGets the value of a custom property, which must bedata-The following conjunctions are named hump. Otherwise, the value of the modified attribute cannot be obtained correctly.
<div data-name-xiaoyang="Little sun"></div>
Copy the code
var oDiv = document.querySelector("div")
var dValue = oDiv.dataset["nameXiaoyang"]	/ / little Yang
Copy the code

1.8 HTML5 web listening interface

, version 1.8.1 ononline

This event is triggered when the network is connected

window.addEventListener("online".function () {
	console.log( "Connected!")})Copy the code

1.8.2 offline

The disconnected hand triggers this event

window.addEventListener("offline".function () {
	console.log( "The network is down!")})Copy the code

1.9 HTML5 full-screen interface

1.9.1 Methods and Properties

  • requestFullScreen(): Enables the full screen display
  • cancelFullScreen(): Exit the full screen display, under different browsers can only use document to achieve, because the whole document exit the full screen
  • fullScreenElement: Indicates whether it is in full screen state
  • Compatible prefix: chorme(webkit), firefox (moz), (IEms), the opera (o)

1.9.2 In full screen Mode

Encapsulation is as follows:

function toFullVideo(obj) {
  if (obj.requestFullscreen) {
    return obj.requestFullScreen();
  } else if (obj.webkitRequestFullScreen) {
    return obj.webkitRequestFullScreen();
  } else if (obj.mozRequestFullScreen) {
    return obj.mozRequestFullScreen();
  } else {
    return obj.msRequestFullscreen()
  }
}
Copy the code

1.9.3 Exiting the Full Screen

Encapsulation is as follows:

function exitFullscreen() {
   if (document.exitFullscreen) {
      document.exitFullscreen();
   } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
   } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
   } else if(document.oRequestFullscreen){
      document.oCancelFullScreen();
   }else {
      document.webkitExitFullscreen(); }}Copy the code

You can also press ESC to exit the full screen

1.9.4 Full Screen Or Not

Encapsulation is as follows:

function isFullScreen() {
 return (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullscreenElement || document.oFullscreenElement || document.msFullscreenElement) ? true : false
}
Copy the code

2.0 HTML 5 – FileReader

2.0.1 readAsText ()

Read the text file (test.txt) and return the text string. The default encoding is UTF-8

2.0.2 readAsBinaryString ()

Read files of any type, return binary string. This method is not used to read the file for display to the user, but to store the file. For example, read the content of a file, obtain binary data, and pass it to the background. After receiving the data, the background stores the data.

The 2.0.3 readAsDataURL ()

  • SRC: specify the path (resource location — URL),srcThe request is for an external file, typically a server resource. It means that he needs to send a request to the server, and he takes up the server’s resources, so we can use itreadAsDataURL()Optimize site loading speed and execution efficiency
  • Read a file to get a segmentdataThe beginning string, the essence of this string is thatDataURL.DataURLIs a scheme for embedding files into documents,DataURLIs to convert the resource tobase64Encoded string form, and store these contents directly in the URL, optimize site loading speed and execution efficiency.
  • abort()Interrupt to read
  • There is no return value, but it will store the read result in the file read objectresultProperties of the
  • You need to pass a parameterbingary large object: files (images or other types that can be embedded in documents)
  • The file is stored in the file form elementfilesProperty is an array.

2.0.4 FileReader event

FileReader provides a complete event model to capture the state of the file at the time it is read

  • onaboutTriggered when reading a file is interrupted
  • onerrorTriggered when a read error occurs
  • onloadTriggered when file read completes successfully
  • onloadendTriggered when the read completes (whether it succeeds or fails)
  • onloadstartTriggered when reading starts
  • onprogressTriggered during file reading

2.0.5 Real-time preview of Files

We will explain how to use it in detail by doing an example of uploading files to live preview.

2.1.0 HTML part

<form action="">
  <input type="file" name="files" id="files"> <br>
  <input type="submit" value="Submit">
  <div id="views"></div>
</form>
Copy the code

2.1.1 JavaScript part

var file = document.getElementById("files")
var views = document.getElementById("views")
file.onchange = function () {
  /* Instantiate the file read object */
  var reader = new FileReader()
  /* The file is stored in the 'files' property of the file form element, which is an array. * /
  var val = file.files
  /* * Requires passing the argument 'bingary Large Object' : file (image or other type that can be embedded into a document) * does not return any value, but it stores the read result in the 'result' property of the file read object * */
  reader.readAsDataURL(val[0])
  reader.onload = function () {
    /* Read the file */
    var res = reader.result
    /* Create an img tag and attach the SRC of the img tag to the newly created tag
    var img = document.createElement('img')
    img.src = res
    img.style.cssText = "width: 200px"
    views.appendChild(img)
  }

}
Copy the code

2.1 HTML 5 drag and drop

2.1.1 Drag events

Applied to the event of the element being dragged

Drag the element, the element to drag

  • ondrag: applies to drag elements that are called throughout the drag process (continuous firing)
  • ondragstart: applies to drag elements and is called when drag begins
  • ondragleave: applies to drag elements, called when the mouse moves away from the drag element
  • ondragend: applies to drag elements and is called when the drag ends

Events applied to the target element

The box we’re dragging it into

  • Ondragenter: Applied to the target element, called when the drag element enters

  • Ondragover: Applied to the target element, called when it stays on the target element

  • Ondrop: Applied to the target element, called when the mouse is released over the target element. Browsers block this event by default, we must block the browser’s default behavior in onDragover: e.preventDefault()

    oBox.ondragover = function (e) {
       e.preventDefault()
    }
    Copy the code
  • Ondragleave: Applied to the target element, called when the mouse moves away from the target element

2.1.2 Case of Dragging boxes

The CSS part

.box1..box2 {
  width: 200px;
  height: 100px;
  border: 1px solid deeppink;
  margin: 10px;
}
p{
  background: darkblue;
  color: #fff;
  font: 12px/40px ' ';
  text-align: center;
}
Copy the code

HTML part

<div class="box1">
  <p draggable="true">I'm a box being dragged</p>
</div>
<div class="box2"></div>
Copy the code

JavaScript part

var oBox1 = document.querySelector(".box1")
var oBox2 = document.querySelector(".box2")
var oP = document.querySelector(".box1 p")
/* box2 drag to box1 */
prevent(oBox1)
oBox1.ondrop = function () {
  this.appendChild(oP)
}
/* box1 drag to box2 */
prevent(oBox2)
oBox2.ondrop = function () {
  this.appendChild(oP)
}
/* Encapsulates the browser default event function */
function prevent(obj) {
  obj.ondragover = function (e) {
    var e = window.event || e
    e.preventDefault()  /* Block the browser's default event */}}Copy the code

But we can see, if there’s a lot of boxes is there a lot of events? So, we can perfect drag by combining the E.target event delegate with datatransfer.setData ().

  • dataTransfer.setData(format, data): format Specifies the type of data (text/ HTML, text/uri-list). Data is generally a string value

Perfect the drag and drop

HTML part
< div id = "box1" > < p draggable = "true" id = "mybox" > I was dragging box < / p > < / div > < div id = "box2" > < / div > < div id = "box3" > < / div >Copy the code
JavaScript part
document.ondragstart = function (e) {
  var e = window.event || e
	/* Save the id of the drag object */
  e.dataTransfer.setData("text/html", e.target.id)
}
	/* Block browser default events */
document.ondragover = function (e) {
  var e = window.event || e
  e.preventDefault()
}
	/* Data stored via datatransfer.setData () can only be retrieved in ondrop events */
document.ondrop = function (e) {
  var e = window.event || e
	/* Get the id */ from getData
  var id = e.dataTransfer.getData("text/html")
	/* Add the previously acquired drag object to the current target object */
  e.target.appendChild(document.getElementById(id))
}
Copy the code

2.2 Geolocation Interface

2.2.1 Method of obtaining location

The data source A little bit disadvantages
The IP address You can do server-side processing anywhere Inaccurate (often error-accurate, usually to the city level) calculations are costly
GPS Very accurate Long positioning time and high power consumption. Poor indoor effect requires additional hardware support
Wi-Fi Accurate, can be used indoors, simple, fast There is no way to use it in rural areas where there are few WiFi access points
Mobile phone signal Very accurate, can be used indoors, simple, fast You need to be able to access the phone or its modem device
User defined More accurate location data can be obtained than programmatic location services, and user input may be faster than automated detection It can be quite inaccurate, especially if the user’s location changes

2.2.2 the navigator. Geolocation. GetCurrentPosition (success, error, option)

  • success: Callback after successfully obtaining geographic information
  • error: Callback after a failure to obtain geographic information
  • option: A way to obtain current geographic information

To test whether the browser supports positioning, support the execution the navigator. Geolocation. GetCurrentPosition does not support the output message

function getLocation() {
  navigator.geolocation ? navigator.geolocation.getCurrentPosition(showPosition, showError, {}) : oMap.innerHTML = 'Geolocation is not supported by this browser'
}
Copy the code

Success callback

The successful callback will pass the geographic information to the successful callback if the geographic information is successfully retrieved

  • position.coords.latitudelatitude
  • position.coords.longitudelongitude
  • position.coords.accuracyprecision
  • position.coords.altitudeThe altitude
function showPosition(position) {
  oMap.innerHTML = "Latitude:" + position.coords.latitude + 

Longitude:
+ position.coords.longitude } Copy the code

Failure callback

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      /* The user rejected the location request */
      oMap.innerHTML = 'User denied the request rot Geolocation'
      break;
    case error.POSITION_UNAVAILABLE:
      /* Location information is not available */
      oMap.innerHTML = 'Location information is unavailable'
      break;
    case error.TIMEOUT:
      /* Request timeout */
      oMap.innerHTML = 'The request to get user location timed out'
      break;
    case error.UNKNOWN_ERR:
      /* Error */
      oMap.innerHTML = 'An unknown error occurred'
      break; }}Copy the code

Option Indicates the method of obtaining the current geographic information

  • enableHighAccuracy: true/falseWhether to use high precision
  • timeout: Sets the timeout period, ms
  • maximumAge: You can set the interval (ms) for the browser to retrieve geographic information
navigator.geolocation.getCurrentPosition(showPosition, showError, {
  enableHighAccuracy: true.timeout: 3000
})
Copy the code

Map case

My secret key: GCDEQ3D0gGadtfbK8P6dcd4GRpUI1aeq

<! DOCTYPEhtml>
<html>
<head>
  <title>General map & Panorama</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=GCDEQ3D0gGadtfbK8P6dcd4GRpUI1aeq"></script>
  <style type="text/css">
    body.html{width: 100%;height: 100%;overflow: hidden;margin:0;font-family:Microsoft Yahei; }#panorama {height: 50%;overflow: hidden; }#normal_map {height:50%;overflow: hidden; }</style>
</head>
<body>
<div id="panorama"></div>
<div id="normal_map"></div>
<script type="text/javascript">
  // Display a panorama
  var panorama = new BMap.Panorama('panorama');
  panorama.setPosition(new BMap.Point(104.072163.30.550424)); // Display panorama according to latitude and longitude coordinates
  panorama.setPov({heading: -40.pitch: 6});

  panorama.addEventListener('position_changed'.function(e){ // When the panorama position is changed, the center point of the normal map also changes
    var pos = panorama.getPosition();
    map.setCenter(new BMap.Point(pos.lng, pos.lat));
    marker.setPosition(pos);
  });
  // Normal map display
  var mapOption = {
    mapType: BMAP_NORMAL_MAP,
    maxZoom: 18.drawMargin:0.enableFulltimeSpotClick: true.enableHighResolution:true
  }
  var map = new BMap.Map("normal_map", mapOption);
  var testpoint = new BMap.Point(104.072163.30.550424);
  map.centerAndZoom(testpoint, 18);
  var marker=new BMap.Marker(testpoint);
  marker.enableDragging();
  map.addOverlay(marker);
  marker.addEventListener('dragend'.function(e){
    panorama.setPosition(e.point); // After dragging the marker, the panorama position also changes
    panorama.setPov({heading: -40.pitch: 6});}
  );
</script>
</body>
</html>
Copy the code

2.3 HTML5- Local Storage

2.3.1 sessionStorage

SessionStorage stores data locally. The storage capacity is about 5M.

  • This data is essentially present in the current page

  • Its life cycle defaults to close the current page and is usually used to store temporary values

  • Sessionstorage. setItem(key,value): stores data as key-value pairs

  • Sessionstorage. getItem(key): obtain data and obtain the corresponding value by specifying the key of the name

  • SessionStorage. RemoveItem (key) : delete data, through the formulation name ke delete the corresponding value

  • Sessionstorage.clear (): Clears all stored contents

<label>Name:<input type="text" id="username"></label>
<input type="button" value="Set value" id="set">
<input type="button" value="Value" id="get">
Copy the code
let username = document.getElementById("username")
let set = document.getElementById("set")
/* Sets the value */
set.onclick = function () {
  let val = username.value
  window.sessionStorage.setItem("userName",val)
}
/ * * / values
get.onclick = function () {
  let val = window.sessionStorage.getItem("userName")
  console.log( val )
}
/* Delete value */ if the key value is incorrect, no error will be reported
remove.onclick = function () {
  window.sessionStorage.removeItem("userName")}Copy the code

2.3.2 localStorage

  • The content stored is about 20 MB
  • Data cannot be shared between different browsers. However, data can be shared in the same browser window
  • Permanently, his data is stored on his hard disk and will not be erased when the page or browser is closed. You must manually clear it if you want to.
  • sessionStorage.setItem(key,value): Stores data as key-value pairs
  • sessionStorage.getItem(key): To obtain data and obtain the corresponding value by specifying the key of the name
  • sessionStorage.removeItem(key): Deletes data by specifying the name ke to delete the corresponding value
  • sessionStorage.clear(): Clears all stored contents
<label>Name:<input type="text" id="username"></label>
<input type="button" value="Set value" id="set">
<input type="button" value="Value" id="get">
<input type="button" value="Delete value" id="remove">
Copy the code
let username = document.getElementById("username")
let set = document.getElementById("set")
let get = document.getElementById("get")
let remove = document.getElementById("remove")
/* Sets the value */
set.onclick = function () {
  let val = username.value
  window.localStorage.setItem("userName",val)
}
/ * * / values
get.onclick = function () {
  let val = window.localStorage.getItem("userName")
  console.log( val )
}
/* Delete the value */
remove.onclick = function () {
  window.localStorage.removeItem("userName")}Copy the code

2.4 HTML5- Application Caching

  • Concept: Using HTML5, it is easy to create offline versions of Web references by creating cache manifest files.

  • Advantage:

    • You can configure the resources to be cached
    • No network Connectionless applications are still available
    • Read cache resources locally, improving the access speed and enhancing user experience
    • Reduce requests and reduce server load

2.4.1 Enabling Application Caching

To enable application caching, include the manifest attribute in the document < HTML > tag:

Manifest =” Path to the application cache manifest file. It is recommended that the file extension be appcahe. This file is essentially a text file.”

<html lang="en" manifest="demo.appcache">
</html>
Copy the code

2.4.2 appcache file

  • # are comments
  • * means cache all files
  • The suggested file extension for the manifest file is: “.appcache”
  • Each manifest page is cached when the user is aligned for access. If the manifest attribute is not specified, the page will not be cached (unless the page is specified directly in the manifest file)
CACHE MANIFEST
#The preceding line must be the first line of the current document, declaring that the document is a cache file

#Here is a list of the listings that need to be cached
CACHE:
images/1.jpg
images/2.jpg

#Configure the list of files that need to be retrieved from the server each time
NETWORK:
images/3.jpg

#If the file cannot be obtained, the specified file is used instead, separated by Spaces
FALLBACK:
images/4.jpg images/tihuan.jpg
Copy the code

Note: the manifest file needs to be configured with the correct MIME-type, that is, “text/cache-manifest”. This must be set up on the Web server

Four, Websocket

  • WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5.

  • WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

  • The HTTP protocol has a flaw: communication can only be initiated by the client. For example, if we want to know today’s weather, the client can only send a request to the server, and the server returns the query result. The HTTP protocol does not allow the server to actively push information to the client.

1.1 introduction

  • WebSocket protocol was born in 2008 and became an international standard in 2011. All browsers already support it.

  • Its biggest characteristic is that the server can take the initiative to push information to the client, the client can also take the initiative to send information to the server, is a real two-way equal dialogue, belongs to a server push technology.

  • Other features include:

    • Based on TCP protocol, the implementation of the server side is relatively easy.
    • It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers.
    • The data format is relatively light, with low performance overhead and high communication efficiency.
    • You can send text or binary data.
    • There are no same-origin restrictions, and clients can communicate with any server.
    • The protocol identifier isws(If encrypted, otherwisewss), the server URL is the URL.

  • The browser sends a request to the server to establish a WebSocket connection through JavaScript. After the connection is established, the client and server can exchange data directly through the TCP connection.

  • When you get a Web Socket connection, you can send data to the server using the send() method and receive the data returned by the server using the onMessage event.

  • The following APIS are used to create WebSocket objects.

    var Socket = new WebSocket(url, [protocol] );
    Copy the code
  • The first parameter in the above code, url, specifies the URL of the connection. The second parameter, protocol, is optional and specifies an acceptable subprotocol.

1.2 the Websocket properties

  • The following are the properties of the WebSocket object. Suppose we created the Socket object using the code above:
attribute describe
Socket.readyState Read-only propertyreadyStateIndicates the connection status, which can be:

0 – Indicates that the connection is not established.

1 – Indicates that the connection is established and communication can be performed.

2 – Indicates that the connection is being closed.

3 – Indicates that the connection is closed or cannot be opened.
Socket.bufferedAmount Read-only propertybufferedAmountThe number of UTF-8 text bytes that have been put into a queue by Send () for transmission, but have not yet been sent.

1.3 the WebSocket event

  • The following are the events related to WebSocket objects. Suppose we created the Socket object using the code above:
The event Event handler describe
open Socket.onopen Triggered when the connection is established
message Socket.onmessage Triggered when the client receives data from the server
error Socket.onerror Triggered when a communication error occurs
close Socket.onclose Triggered when the connection is closed

1.4 the WebSocket method

  • The following are methods for WebSocket objects. Suppose we created the Socket object using the code above:
methods describe
Socket.send() Use the connection to send data
Socket.close() Close the connection

1.5 the WebSocket instance

  • The WebSocket protocol is essentially a TCP – based protocol.
  • To establish a WebSocket connection, the client browser first issues an HTTP request to the server. This request is different from the usual HTTP request and contains some additional header information, including “Upgrade: “WebSocket” indicates that this is an HTTP request for a protocol upgrade. The server parses these additional headers and generates a reply message back to the client. The WebSocket connection between the client and the server is established, and the two sides can communicate freely through the connection channel. And the connection persists until either the client or the server actively closes the connection.

1.5.1 HTML and JavaScript on the client

  • Most browsers currently support the WebSocket() interface, so you can try it out in Chrome, Mozilla, Opera, and Safari.
<! --runoob_websocket.html -->
<! DOCTYPEHTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>document</title>
    
      <script type="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in window)
            {
               alert("Your browser supports WebSocket!");
               // The WebSocket object is used as a constructor to create a new WebSocket instance.
               var ws = new WebSocket("ws://localhost:9998/echo");
               ws.onopen = function() {
                  // The Web Socket is connected, use the send() method to send data
                  ws.send("Send data");
                  alert("Data in transit...");
               };
                
               ws.onmessage = function (event) { 
                 // Note that the server data can be either text or binary (bloB objects or Arraybuffer objects).
                  if(typeof event.data === String) {
                    var received_msg = event.data;
                    console.log("Received data string");
                  }

                 if(event.data instanceof ArrayBuffer) {var buffer = event.data;
                   console.log("Received arraybuffer");
                 }
                  alert("Data received...");
               };
                
               ws.onclose = function() { 
                  / / close the websocket
                  alert("Connection closed..."); 
               };
            } else {
               // Browsers do not support WebSocket
               alert("Your browser does not support WebSocket!"); }}</script>
        
   </head>
   <body>
      <div id="sse">
         <a href="javascript:WebSocketTest()">Run the WebSocket</a>
      </div>
   </body>
</html>
Copy the code