[关闭]
@EncyKe 2015-12-24T04:16:45.000000Z 字数 18757 阅读 2366

HTML5

前端



一、简介

1. 新功能

  1. 添加了新元素标签:
    <header>:定义 section 或 page 的页眉;
    <hgroup>:标题群组;
    <nav>:定义导航链接;
    <section>:定义 section;
    <aside>:定义页面内容之外的内容;
    <footer>:定义 section 或 page 的页脚;
    <datalist>:定义下拉列表;
    <audio>:定义声音内容;
    <source>:定义媒介源;
    <video>:定义视频;
    <wbr>:定义视频;
    <command>:定义命令按钮;
    <time>:定义日期/时间;
    <bdi>:定义文本的文本方向,使其脱离其周围文本的方向设置;
    <mark>:定义有记号的文本;
    <meter>:定义预定义范围内的度量;
    <progress>:定义任何类型的任务的进度;
    <rp>:定义若浏览器不支持 ruby 元素显示的内容;
    <rt>:定义 ruby 注释的解释;
    <ruby>:定义 ruby 注释;
    <keygen>:定义生成密钥;
    <output>:定义输出的一些类型;
    <track>:定义用在媒体播放器中的文本轨道;
    <details>:定义元素的细节;
    <dialog>:定义对话框或窗口;
    <summary>:为 元素定义可见的标题;
    <embed>:为外部应用程序(非 HTML)定义容器;
  2. Canvas二维绘图界面控制JS编程;
  3. 无须第三方插件即可嵌入视频;
  4. 无须第三方插件即可永久性本地数据存储;
  5. 离线Web应用运作;
  6. 地理定位;
  7. Web表单经过改进。

2. 其它

  1. Modernizr库
  2. jQuery库:减少和简化处理DOM、使用Ajax;
  3. CDN调用:
    • Google:<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    • Microsoft:··
  4. SVG:可缩放矢量图形,需以XML指定;
  5. 离线web应用:<html manifest="notetoself.manifest">,其中notetoself.manifest含:CACHE MANIFEST以及CACHE(此节存放要缓存的图片);AddType text/cache-manifest .manfest
  6. Web Socket API:XMLHttpRequest以及JSONP都是基于http协议,web socket则基于ws协议;
  7. 拖放元素API:draggable: true;
  8. querySelectorAlldocument.querySelectorAll(""); 选取CSS选择器,语法同CSS;querySelector:语法同上;

二、表单

表单HTML模板

  1. <form id="" method="">
  2. <hgroup>
  3. </hgroup>
  4. <fieldset>
  5. <legend>
  6. </legend>
  7. <div>
  8. <label for="">
  9. </label>
  10. <input id="" name="" placeholder="(文本占位符)"
  11. type=""
  12. required aria-required="true"(必填项 range/color/button/hidden不可用)
  13. autofocus(光标跟随)
  14. autocomplete="off"(禁止浏览器自动填写 可加在form本身上)
  15. list="_(自定义名称,在新的datalist下拉弹出选项)"
  16. />
  17. <datalist id="(上述list名称)" >
  18. <select>
  19. <option value=""></option>
  20. <option value=""></option>
  21. <option value=""></option>
  22. </select>
  23. </datalist>
  24. </div>
  25. </fieldset>
  26. </form>

三、多媒体

多媒体HTML模板 & Video/Audio 参考手册

  1. <video
  2. id=""
  3. src=""
  4. width="" height=""
  5. controls (显示按钮,控制按钮的外观应浏览器不同而不同)
  6. autoplay (自动播放,不建议)
  7. preload="auto/none/metadata" (播放前是否下载视频)
  8. loop (循环播放)
  9. poster="" (视频缩略图路径)
  10. >
  11. <source src="video/preroll.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
  12. (Mp4格式:Safari, IE9+)
  13. <source src="video/preroll.ogv" type='video/ogg; codecs="theora, vorbis"'>
  14. (ogv格式:FF, Opera)
  15. <source src="video/preroll.webm" type='video/webm; codecs="vp8, vorbis"'>
  16. (WebM格式:Chrome)
  17. <p>Sorry, your browser doesn't support the video element</p> (指出浏览器不兼容video)
  18. </video>

1. 视频

1) 视频编码

HTML5规范允许采用任何视频格式,但具体的支持由浏览器决定——
Mp4容器:H.264视频编码+AAC音频编码;
WebM容器:Vp8视频编码+Vorbis音频编码;
Ogg容器:Theora视频编码+Vorbis音频编码;

2) 连续播放列表

  1. var position = 0;
  2. var playlist;
  3. var video;
  4. window.onload = function() {
  5. playlist = ["video/preroll",
  6. "video/areyoupopular",
  7. "video/destinationearth"];
  8. video = document.getElementById('video');
  9. video.addEventListener("ended", nextVideo, false);
  10. //addEventListener()方法增加事件监听:
  11. //“ended”表视频播放结束,调用函数,默认一般为flase(除非编写高级代码)
  12. video.src = playlist[position] + getFormatExtension();
  13. video.load(); //加载视频
  14. video.play(); //播放视频
  15. };
  16. function nextVideo() {
  17. position++;
  18. if (position >= playlist.length) {
  19. position = 0;
  20. }
  21. video.src = playlist[position] + getFormatExtension();
  22. video.load();
  23. video.play();
  24. }
  25. function getFormatExtension() {
  26. if (video.canPlayType("video/mp4") != "") {
  27. return ".mp4";
  28. } else if (video.canPlayType("video/ogg") != "") {
  29. return ".ogv";
  30. } else if (video.canPlayType("video/webm") != "") {
  31. return ".webm";
  32. }
  33. }
  34. //canPlayType()方法将返回三个值:"probably"、"maybe"、""(空串表完全无法播放)

3) 自定义播放控件

  1. function setEffect(e) {
  2. var id = e.target.getAttribute("id");
  3. if (id == "normal") {
  4. pushUnpushButtons("normal", ["western", "noir", "scifi"]);
  5. effectFunction = null;
  6. } else if (id == "western") {
  7. pushUnpushButtons("western", ["normal", "noir", "scifi"]);
  8. effectFunction = western;
  9. } else if (id == "noir") {
  10. pushUnpushButtons("noir", ["normal", "western", "scifi"]);
  11. effectFunction = noir;
  12. } else if (id == "scifi") {
  13. pushUnpushButtons("scifi", ["normal", "western", "noir"]);
  14. effectFunction = scifi;
  15. }
  16. }
  17. //以上四个按钮为单选按钮,调用下文的pushUnpushButton函数
  18. function handleControl(e) {
  19. var id = e.target.getAttribute("id");
  20. var video = document.getElementById("video");
  21. if (id == "play") {
  22. pushUnpushButtons("play", ["pause"]);
  23. if (video.ended) {
  24. video.load();
  25. }
  26. video.play();
  27. } else if (id == "pause") {
  28. pushUnpushButtons("pause", ["play"]);
  29. video.pause();
  30. } else if (id == "loop") {
  31. if (isButtonPushed("loop")) {
  32. pushUnpushButtons("", ["loop"]);
  33. } else {
  34. pushUnpushButtons("loop", []);
  35. }
  36. video.loop = !video.loop; //取反值
  37. } else if (id == "mute") {
  38. if (isButtonPushed("mute")) {
  39. pushUnpushButtons("", ["mute"]);
  40. } else {
  41. pushUnpushButtons("mute", []);
  42. }
  43. video.muted = !video.muted; //取反值
  44. }
  45. }
  46. //play和pause是单选按钮,但loop和mute为开关按钮
  47. function pushUnpushButtons(idToPush, idArrayToUnpush) {
  48. if (idToPush != "") {
  49. var anchor = document.getElementById(idToPush);
  50. var theClass = anchor.getAttribute("class");
  51. if (!theClass.indexOf("selected") >= 0) {
  52. theClass = theClass + " selected";
  53. anchor.setAttribute("class", theClass);
  54. var newImage = "url(images/" + idToPush + "pressed.png)";
  55. anchor.style.backgroundImage = newImage; //通过改变CSS中的背景图片实现
  56. }
  57. }
  58. for (var i = 0; i < idArrayToUnpush.length; i++) {
  59. anchor = document.getElementById(idArrayToUnpush[i]);
  60. theClass = anchor.getAttribute("class");
  61. if (theClass.indexOf("selected") >= 0) {
  62. theClass = theClass.replace("selected", "");
  63. anchor.setAttribute("class", theClass);
  64. anchor.style.backgroundImage = "";
  65. }
  66. }
  67. }
  68. //pushUnpushButton函数实现单选效果按钮
  69. function isButtonPushed(id) {
  70. var anchor = document.getElementById(id);
  71. var theClass = anchor.getAttribute("class");
  72. return (theClass.indexOf("selected") >= 0);
  73. }
  74. //isButtonPushed判定按钮是否被触发
  75. function endedHandler(e) {
  76. pushUnpushButtons("", ["play"]);
  77. }
  78. //播放完毕后play按钮弹起

4) 利用canvas为video加滤镜:

需用两个canvas遮罩video,#buffer用作缓冲区,#display显示视频:

  1. <video id="video" width="720" height="480"></video>
  2. <canvas id="buffer" width="720" height="480"></canvas>
  3. <canvas id="display" width="720" height="480"></canvas>
  1. video.addEventListener("play", processFrame, false); //放在window.onload中
  2. function processFrame(e) {
  3. var video = document.getElementById("video");
  4. if (video.paused || video.ended) {
  5. return;
  6. }
  7. var bufferCanvas = document.getElementById("buffer");
  8. var displayCanvas = document.getElementById("display");
  9. var buffer = bufferCanvas.getContext("2d");
  10. var display = displayCanvas.getContext("2d");
  11. buffer.drawImage(video, 0, 0, bufferCanvas.width, displayCanvas.height);
  12. //drawImage方法:取一图像并把它绘制在canvas上,指定x、y以及宽、高;
  13. //若指定video为源,则可选取视频帧;
  14. var frame = buffer.getImageData(0, 0, bufferCanvas.width, displayCanvas.height);
  15. //getImageData方法:取图像的rgba四项信息生成数组;
  16. var length = frame.data.length / 4;
  17. //得出帧数据的长度,即一帧的像素数;
  18. for (var i = 0; i < length; i++) {
  19. var r = frame.data[i * 4 + 0];
  20. var g = frame.data[i * 4 + 1];
  21. var b = frame.data[i * 4 + 2];
  22. if (effectFunction) {
  23. effectFunction(i, r, g, b, frame.data); //传入要作处理的滤镜函数
  24. }
  25. }
  26. display.putImageData(frame, 0, 0);
  27. //处理完毕后,显示在canvas#display上;
  28. setTimeout(processFrame, 0);
  29. //要求再次尽快重复运行processFrame函数,使每一帧都能得到处理
  30. }
  31. function bwcartoon(pos, r, g, b, outputData) {
  32. var offset = pos * 4;
  33. if( outputData[offset] < 120 ) {
  34. outputData[offset] = 80;
  35. outputData[++offset] = 80;
  36. outputData[++offset] = 80;
  37. } else {
  38. outputData[offset] = 255;
  39. outputData[++offset] = 255;
  40. outputData[++offset] = 255;
  41. }
  42. outputData[++offset] = 255;
  43. ++offset;
  44. } //卡通滤镜
  45. function noir(pos, r, g, b, data) {
  46. var brightness = (3*r + 4*g + b) >>> 3;
  47. if (brightness < 0) brightness = 0;
  48. data[pos * 4 + 0] = brightness;
  49. data[pos * 4 + 1] = brightness;
  50. data[pos * 4 + 2] = brightness;
  51. } //黑白滤镜
  52. function western(pos, r, g, b, data) {
  53. var brightness = (3*r + 4*g + b) >>> 3;
  54. data[pos * 4 + 0] = brightness+40;
  55. data[pos * 4 + 1] = brightness+20;
  56. data[pos * 4 + 2] = brightness-20;
  57. data[pos * 4 + 3] = 255; //220;
  58. } //西部片滤镜
  59. function scifi(pos, r, g, b, data) {
  60. var offset = pos * 4;
  61. data[offset] = Math.round(255 - r) ;
  62. data[offset+1] = Math.round(255 - g) ;
  63. data[offset+2] = Math.round(255 - b) ;
  64. } //底片滤镜

5) 处理错误

1 = MEDIA_ERR_ABORTED:取回过程被用户中止;
2 = MEDIA_ERR_NETWORK:当下载时发生错误;
3 = MEDIA_ERR_DECODE:当解码时发生错误;
4 = MEDIA_ERR_SRC_NOT_SUPPORTED:不支持音频/视频。

2. 音频

与视频基本相同,改<video><audio>,无widthheight以及poster
格式:mp3wavOgg Vorbis


四、地理位置感知

1. 定位原理

  1. GPS(能耗大);
  2. IP地址映射物理位置(街区级);
  3. 蜂窝电话(取决于用户周围的基站数);
  4. WiFi三角定位(要求处于静态);
  5. 其它。

2. 调用谷歌地图

  1. <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
  2. <!--true值指谷歌地图将调用用户的位置,false表不调用位置-->

更多谷歌地图API:http://code.google.com/apis/maps/documentation/javascript/

3. geolocation对象下的getCurrentPositionwatchPositionclearWatch方法:

  1. getCurrentPosition(showLocation, errorHandler, positionOptions);
  2. showLocationposition对象:coords属性、timestamp属性;
  3. coordinates对象:latitudelongitudeaccuracyaltitudealtitudeAccuracyheadingspeed
  4. positionOptionenableHighAccuracytruefalse, //是否以高性能换取定位的精确性
  5. timeoutinfinity、数值(毫秒),//定位需要多长时间,超出这一期限则报为error
  6. maximumAge:数值(毫秒)//最多可套用多久前的缓存位置

4. 将度分秒转化为小数(西经、南纬为负数值)

  1. function degreesToDecimal(degrees, minutes, seconds){
  2. return degrees + (minutes / 60) + (seconds / 3600.0);
  3. }

地理定位模板

  1. var watchId = null;
  2. var map = null;
  3. var ourCoords = {
  4. latitude: 47.624851,
  5. longitude: -122.52099
  6. };
  7. var prevCoords = null;
  8. window.onload = getMyLocation;
  9. function getMyLocation() {
  10. if (navigator.geolocation) {
  11. navigator.geolocation.getCurrentPosition(
  12. displayLocation,
  13. displayError,
  14. {enableHighAccuracy: true, timeout:9000});
  15. var watchButton = document.getElementById("watch");
  16. watchButton.onclick = watchLocation;
  17. var clearWatchButton = document.getElementById("clearWatch");
  18. clearWatchButton.onclick = clearWatch;
  19. }
  20. else {
  21. alert("Oops, no geolocation support");
  22. }
  23. //测试能否实现地理定位
  24. }
  25. function displayLocation(position) {
  26. var latitude = position.coords.latitude;
  27. var longitude = position.coords.longitude;
  28. //实现地理定位的代码
  29. var div = document.getElementById("location");
  30. div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
  31. div.innerHTML += " (with " + position.coords.accuracy + " meters accuracy)";
  32. //引用地理定位
  33. var km = computeDistance(position.coords, ourCoords);
  34. var distance = document.getElementById("distance");
  35. distance.innerHTML = "You are " + km + " km from the WickedlySmart HQ";
  36. //引用距离测量
  37. if (map == null) {
  38. showMap(position.coords);
  39. prevCoords = position.coords;
  40. }
  41. else {
  42. var meters = computeDistance(position.coords, prevCoords) * 1000;
  43. if (meters > 20) {
  44. scrollMapToPosition(position.coords);
  45. prevCoords = position.coords;
  46. }
  47. }
  48. }
  49. function computeDistance(startCoords, destCoords) {
  50. var startLatRads = degreesToRadians(startCoords.latitude);
  51. var startLongRads = degreesToRadians(startCoords.longitude);
  52. var destLatRads = degreesToRadians(destCoords.latitude);
  53. var destLongRads = degreesToRadians(destCoords.longitude);
  54. var Radius = 6371; // radius of the Earth in km
  55. var distance = Math.acos(Math.sin(startLatRads) * Math.sin(destLatRads) +
  56. Math.cos(startLatRads) * Math.cos(destLatRads) *
  57. Math.cos(startLongRads - destLongRads)) * Radius;
  58. return distance;
  59. }
  60. function degreesToRadians(degrees) {
  61. radians = (degrees * Math.PI)/180;
  62. return radians;
  63. }
  64. //实现距离测量的代码
  65. function showMap(coords) {
  66. var googleLatAndLong = new google.maps.LatLng(coords.latitude,
  67. coords.longitude);
  68. var mapOptions = {
  69. zoom: 10,
  70. center: googleLatAndLong,
  71. mapTypeId: google.maps.MapTypeId.ROADMAP//SATELLITE:卫星图;HYBRID:混合
  72. };
  73. var mapDiv = document.getElementById("map");
  74. map = new google.maps.Map(mapDiv, mapOptions);
  75. var title = "Your Location";
  76. var content = "You are here: " + coords.latitude + ", " + coords.longitude;
  77. addMarker(map, googleLatAndLong, title, content);
  78. // 标记弹窗信息
  79. }
  80. //引用谷歌地图
  81. function addMarker(map, latlong, title, content) {
  82. var markerOptions = {
  83. position: latlong,
  84. map: map,
  85. title: title,
  86. clickable: true
  87. };
  88. var marker = new google.maps.Marker(markerOptions);
  89. var infoWindowOptions = {
  90. content: content,
  91. position: latlong
  92. };
  93. var infoWindow = new google.maps.InfoWindow(infoWindowOptions);
  94. google.maps.event.addListener(marker, 'click', function() {
  95. infoWindow.open(map);
  96. });
  97. }
  98. //大头钉标记以及单击弹出窗口的代码
  99. function displayError(error) {
  100. var errorTypes = {
  101. 0: "Unknown error",
  102. 1: "Permission denied",
  103. 2: "Position is not available",
  104. 3: "Request timeout"
  105. };
  106. var errorMessage = errorTypes[error.code];
  107. if (error.code == 0 || error.code == 2) {
  108. errorMessage = errorMessage + " " + error.message;
  109. }
  110. var div = document.getElementById("location");
  111. div.innerHTML = errorMessage;
  112. }
  113. //处理错误类型的代码
  114. function watchLocation() {
  115. watchId = navigator.geolocation.watchPosition(
  116. displayLocation,
  117. displayError,
  118. {enableHighAccuracy: true, timeout:3000});
  119. }
  120. // 开始监视的代码
  121. function scrollMapToPosition(coords) {
  122. var latitude = coords.latitude;
  123. var longitude = coords.longitude;
  124. var latlong = new google.maps.LatLng(latitude, longitude);
  125. map.panTo(latlong);
  126. // 新标记
  127. addMarker(map, latlong, "Your new location", "You moved to: " +
  128. latitude + ", " + longitude);
  129. }
  130. // 路径标记的代码
  131. function clearWatch() {
  132. if (watchId) {
  133. navigator.geolocation.clearWatch(watchId);
  134. watchId = null;
  135. }
  136. }
  137. // 清除监视的代码

五、画布

  1. canvas可有可多,但应注明id,因为canvas是通过JS进行绘制的;
  2. canvas默认是透明的;
  3. canvas默认宽300px、高150px,建议是在标签属性中指明宽、高,而非通过css(css指定将产生缩放效果);
  4. 欲绘制canvas,需先创建一个context;
  1. <canvas width="600" height="200" id="">
  2. <p>You need canvas to use XXX!</p>
  3. <p>This example requires a browser that supports the
  4. <a href="http://www.w3.org/html/wg/html5/">HTML5</a>
  5. &lt;canvas&gt; feature.</p>
  6. <!--此处文字在不支持canvas的浏览器将显示-->
  7. </canvas>

画布模板 & canvas参考手册

  1. window.onload = function() {
  2. var button = document.getElementById("previewButton");
  3. button.onclick = previewHandler;
  4. makeImage();
  5. }
  6. function previewHandler() {
  7. var canvas = document.getElementById("tshirtCanvas");//按id选取canvas
  8. var context = canvas.getContext("2d");//2d的context指定,3d尚未出现
  9. fillBackgroundColor(canvas, context);
  10. var selectObj = document.getElementById("shape");
  11. var index = selectObj.selectedIndex;
  12. //selectedIndex表选取数组字符串对应的序数,注意第一个为0
  13. var shape = selectObj[index].value;
  14. //value表按上述序数取字符串
  15. if (shape == "squares") {
  16. for (var squares = 0; squares < 20; squares++) {
  17. drawSquare(canvas, context);//编写随机生成的伪函数
  18. }
  19. }
  20. else if (shape == "circles") {
  21. for (var circles = 0; circles < 20; circles++) {
  22. drawCircle(canvas, context);
  23. }
  24. }
  25. drawText(canvas, context);
  26. drawBird(canvas, context);
  27. }
  28. function fillBackgroundColor(canvas, context) {
  29. var selectObj = document.getElementById("backgroundColor");
  30. var index = selectObj.selectedIndex;
  31. var bgColor = selectObj[index].value;
  32. context.fillStyle = bgColor;
  33. context.fillRect(0, 0, canvas.width, canvas.height);
  34. //fillRect表画矩形带填充色,默认为黑色,语法:fillRect(x,y,width,height);
  35. //strokeRect则表画矩形仅轮廓
  36. }
  37. function drawSquare(canvas, context) {
  38. var w = Math.floor(Math.random() * 40);
  39. //random取随机,floor取整,40界定上界
  40. var x = Math.floor(Math.random() * canvas.width);
  41. var y = Math.floor(Math.random() * canvas.height);
  42. context.fillStyle = "rgb(0, 173, 239)";
  43. //fillStyle表填充色:context.fillStyle = "lightblue";
  44. context.fillRect(x, y, w, w);
  45. }
  46. function drawCircle(canvas, context) {
  47. var radius = Math.floor(Math.random() * 40);
  48. var x = Math.floor(Math.random() * canvas.width);
  49. var y = Math.floor(Math.random() * canvas.height);
  50. context.beginPath();
  51. /*
  52. 路径方法(画三角形为例):
  53. context.beginPath();
  54. context.moveTo(_,_);
  55. context.lineTo(_,_);
  56. context.lineTo(_,_);
  57. context.closePath();
  58. context.lineWidth=5; 路径线宽为5
  59. context.stroke(); 用线描绘路径
  60. context.fillStyle="red";填充颜色为红
  61. context.fill(); 用颜色填充路径封闭区域
  62. */
  63. context.arc(x, y, radius, 0, degreesToRadians(360), true);
  64. //arc方法:context.arc(x, y, radius, startAngle, endAngle, direction);
  65. //x,y确定圆心坐标;radius指定半径;
  66. //startAngle与endAngle表弧的起始角和终止角,单位弧度,取值正负,0为x轴正方向;
  67. //direction规定创建圆路径的方向,true为逆时针;
  68. context.fillStyle = "lightblue";
  69. context.fill();
  70. }
  71. function degreesToRadians(degrees) {
  72. return (degrees * Math.PI)/180;
  73. //degreesToRadians()方法将角度转换为弧度;
  74. }

六、通信

  1. function getSales() {
  2. var url = ""; //浏览器从哪里请求数据
  3. var request = new XMLHttpRequest(); //XMLHttpRequest是一个构造函数
  4. request.open("GET", url); //HTTP GET是获取HTTP数据的标准方法,open方法建立请求
  5. request.onload = function() {
  6. if (request.status == 200) { //200表调用成功的返回值
  7. updateSales(request.responseText);
  8. }
  9. };
  10. request.send(null); //将请求发送至服务器,null指不发送数据
  11. }
  1. XMLHttpRequest:给一个url,即可为用户获取数据,并置入处理程序。可以获取XML,也可是JSON。
  2. JSON (JavaScript Object Notation):规模、可读性高,是js的内置记法。
    JSON.stringify()方法:把js对象作为实参传入,成为一个字符串;
    JSON.parse()方法:把字符串转换为一个对象;
  3. XMLHttpRequest不允许跨域请求,这是浏览器的安全策略;若需跨域请求,需用JSONP (JSON with Padding),前提是被请求的服务器支持JSON,如Google、Facebook、Twitter、MS等。
  4. JSONP:Padding是指传回的JSON经历了一个函数调用包装。由于是从第三方库或者其它服务器请求数据,JSONP方法通常不是很安全,除非是值得信任的库,如Google、Facebook、Twitter、MS等。
    “web应用的一大优点就是不必像web页面那样不断刷新。”
  5. setInterval()方法:定时调用、处理的方法。setInterval(函数名, 毫秒数值)。关闭浏览器终止计时,或以clearInterval方法终止。
  6. createElement方法、setAttribute方法、getElementsByTagName方法(获取后用数组取值[]取标签的次序)、appendChild方法、replaceChild方法(replaceChild (NEW, OLD);

通信模板

  1. window.onload = init;
  2. function init() {
  3. var interval = setInterval(handleRefresh, 3000);
  4. handleRefresh();
  5. }
  6. function handleRefresh() {
  7. console.log("here");
  8. var url = "http://gumball.wickedlysmart.com" +
  9. "?callback=updateSales" +
  10. //"&lastreporttime=" + lastReportTime +
  11. "&random=" + (new Date()).getTime(); //创建新的url骗过浏览器,旨在清除缓存
  12. var newScriptElement = document.createElement("script"); //以下皆为创建新的script过程
  13. newScriptElement.setAttribute("src", url);
  14. newScriptElement.setAttribute("id", "jsonp");
  15. var oldScriptElement = document.getElementById("jsonp");
  16. var head = document.getElementsByTagName("head")[0];
  17. if (oldScriptElement == null) {
  18. head.appendChild(newScriptElement);
  19. }
  20. else {
  21. head.replaceChild(newScriptElement, oldScriptElement);
  22. }
  23. }

七、Web工作线程

  1. JS是单线程的,实现多线程需用Web worker API;
  2. 工作线程代码单独放在一个JS文件里;
  3. 工作线程不能访问页面的DOM或函数,但可使用XMLHttpRequestlocalStorage
  4. postMessage可以向工作线程发送字符串、数组和对象,但不能发送函数;
  5. 工作线程将其onmessage属性设置为一个处理函数,来接收页面发送的消息;
  6. 工作线程结果封装在一个event对象中,并置于data属性中;
  7. event.target可以查找哪个工作线程发出了消息;
  8. 可从页面用worker.terminate()终止一个线程,也可在工作线程中用close()自己终止;
  9. importScripts可以在线程中使用JS库,也可以利用JSONP;

Web工作线程模板

  1. window.onload = function() {
  2. if (Worker == "undefined") {
  3. document.getElementById("output").innerHTML = "Bummer, no Web Workers";
  4. //查看是否支持web工作线程
  5. }
  6. else {
  7. var worker = new Worker("worker.js");
  8. //创建工作线程,可以有多个且不同的js:
  9. /*
  10. var worker = new Worker("worker.js");
  11. var worker2 = new Worker("worker.js");
  12. var worker3 = new Worker("another_worker.js");
  13. */
  14. worker.postMessage("ping");
  15. //postMessage方法可以发送字符串、数组、JSON对象等,但不能发送函数
  16. worker.onmessage = function(event) {
  17. var message = "Worker " + " says " + event.data;
  18. document.getElementById("output").innerHTML = message;
  19. }
  20. //onmessage:接收到的消息包装与event对象中,含两个属性:data及target
  21. worker.onerror = function(error) {
  22. document.getElementById("output").innerHTML =
  23. "There was an error in " + error.filename +
  24. " at line number " + error.lineno +
  25. ": " + error.message;
  26. };
  27. }
  28. }

八、本地存储

  1. Web存储包括本地存储localStorage和会话存储sessionStorage;
  2. 本地存储是持久的,会话存储在关闭窗口或退出浏览器时将自行清除;二者API完全一致;
  3. 每个域有5M的本地存储,域间的数据项是互不可见的;
  4. localStorage.setItem(key)可以增加一个值;
  5. localStorage.getItem(key)可以获取一个值;
  6. localStorage.key()方法可以列出localStorage中的键;
  7. F12开发者工具下resources可以查看、编辑键值对;
  8. 删除方法:removeItem(key)clear
  9. 每个键必须是唯一的,否则最新的数据项将覆盖原有的;
  10. 建议用getTime()方法,以时间生成唯一的键;
  11. 若要存储更复杂的数据,可用JSON,以JSON.stringify转化为字符串,以JSON.parse转化为对象;

本地存储模板

  1. localStorage.setItem("sticky_0", "Pick up dry cleaning");
  2. //localStorage对象:
  3. //setItem方法:setItem("键的自定义字符串","值的自定义字符串"),键及值都需采用字符串形式
  4. //字符串可用parseInt或parseOut转换为数值
  5. /*
  6. 另可用关联数组语法:
  7. localStorage["sticky_0"]="Pick up dry cleaning";
  8. var sticky=lovalStorage["sticky_0"];
  9. */
  10. localStorage.setItem("sticky_1", "Cancel cable tv, who needs it now?");
  11. var stickyValue = localStorage.getItem("sticky_0");
  12. alert(stickyValue);
  13. window.onload = init;
  14. function init() {
  15. var button = document.getElementById("add_button");
  16. button.onclick = createSticky;
  17. for (var i = 0; i < localStorage.length; i++) {
  18. //length属性给出localStorage的键值对的数目;
  19. var key = localStorage.key(i);
  20. //key方法可以给出localStorage中各项的键;
  21. //语法:localStorage.key(i)取值;localStorage[key]返回;
  22. if (key.substring(0, 6) == "sticky") {
  23. var value = localStorage.getItem(key);
  24. addStickyToDOM(value);
  25. }
  26. }
  27. }
  28. function createSticky() {
  29. var value = document.getElementById("note_text").value;
  30. var key = "sticky_" + localStorage.length;
  31. //数组起始序数为0,可以length递增1;
  32. localStorage.setItem(key, value);
  33. addStickyToDOM(value);
  34. }
  35. function addStickyToDOM(value) {
  36. var stickies = document.getElementById("stickies");
  37. var sticky = document.createElement("li");
  38. var span = document.createElement("span");
  39. span.setAttribute("class", "sticky");
  40. span.innerHTML = value;
  41. sticky.appendChild(span);
  42. stickies.appendChild(sticky);
  43. }


添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注