語義化標籤 input的新屬性值 表單的驗證 json的新方法 自定義屬性 拖放 canvas 地理位置的獲取 離線存儲 本地存儲 audio videocss
使用最多的id->當前的語義化標籤
頁面總體架構
header標籤 頁面頭部或者板塊的頭部
footer標籤 頁面底部或者板塊的底部
nav標籤 頁面的導航
hgroup 頁面中的標題組合
內容部分
section 頁面中用來劃分區域的 劃分出獨立的區塊
article 結構完整而且內容相對獨立的一部分
aside 和主題相關的附屬信息
相對獨立的語義化的新標籤
figure 媒體元素組合(圖片+文字) img+figcaption
time 時間標籤 標籤有一個datatime屬性
dataList 列表標籤 input中可能會輸入的值html
<input type="text" list="list1" > <datalist id="list1"> <option value="js">sasa1</option> <option value="css">sasa2</option> <option value="html">sasa3</option> </datalist>
details 標籤 配合summary前端
<details> //加上open屬性 p的內容就會顯示 <summary>sasa</summary> <p>sassasas</p> </details>
實現了點擊summary的時候會顯示p中的內容
dialog 標籤html5
<dialog open> <dt>老叟</dt> <dd>老叟</dd> <dt>老叟</dt> <dd>老叟</dd> <dt>老叟</dt> <dd>老叟</dd> </dialog>
必須加上open屬性 才能顯示整個對話框
address 標籤 頁面上的地址 傾斜
mark 標籤 標記一下 文字的背景變黃
功能性標籤
progress 進度條node
<progress value="50" max="100"></progress>
瀏覽器h5的兼容 頁面開始的地方添加腳本git
<script> document.createElement("header") document.createElement("nav") document.createElement("section") document.createElement("footer") </script>
等一系列新的結構性的標籤、兼容低版本瀏覽器的插件 html5.jsweb
email 輸入的必須爲email
tel 輸入的必須爲一個電話號
url 輸入的必須爲一個網址
search 搜索框 輸入的過程當中 輸入框尾部總有一個X 一點擊X輸入的內容就沒有了
range 數值選擇器 step=2 min=0 max=10 value=當前的值
number 輸入框的尾部 有向上和向下的箭頭 會改變數值
color 顏色輸入框
datetime 顯示完整的日期
time 小時和分鐘數的顯示
week 周顯示器 顯示當前是這一年的第幾周
month 月顯示器 顯示當前是這一年的第幾月ajax
placeholder 輸入框內會默認顯示的值
autocomplete 輸入的過程當中是否會自動提示 若是在公共電腦上不須要保存的話 autocomplete =「off」
autofocus 表單是否會自動獲取焦點 直接使用沒有值
input 的list屬性指定這個輸入框的datalist
required 在提交以前這個輸入 這個字段是必填的
pattern 屬性值爲正則表達式 能夠校驗這個輸入的字符串 在失去焦點的時候就會校驗
formaction 這個輸入框單獨的提交地址 傳統的都是整個表單會提交到一個地方 在opera能夠正則表達式
htmljson
<form> <input type="text" required id="text"/> <input type="submit"/> </form>
js
var oText=document.getElementById("text"); //只有再沒有填寫在這個字段 而且提交的時候纔會觸發這個事件 oText.addEventListener("invalid",fn,false); //用戶向輸入框中輸入文字的時候便會觸發該事件 oText.oninput=function () { console.log(112) //自定義驗證 if(this.value=="111"){ this.setCustomValidity("這是銘感詞") }else{ this.setCustomValidity("這是銘感詞") } } function fn() { console.log(this.validity) //整個驗證信息都是保存在這個對象當中的 console.log(this.validity.valid) //布爾值 驗證經過爲true console.log(this.validity.valueMissing) //布爾值 輸入的字符串是否爲空 console.log(this.validity.typeMismatch) //布爾值 輸入的字符串是否和要求的類型不一致返回true console.log(this.validity.patternMismatch) //布爾值 輸入的字符串是否和pattern的屬性值的正則是否不匹配 返回爲true console.log(this.validity.tooLong) //布爾值 輸入的字符串的長度大於maxlength的屬性值 }
在設計 保存至草稿箱按鈕的時候注意
一、關閉表單驗證 爲這個input 添加formnovalidate 關閉驗證
二、使用formaction 提交到本地
querySelector(id,class[只能選擇到一組中的第一個元素],標籤) 返回的都是一個元素
html
<div id="test2">sasa</div>
js
window.onload=function () { var oDIv=document.querySelector('#test2') oDIv.style.background="red" }
querySelectorAll(id,class[選擇到一組元素],標籤)
html5增長了對元素類的操做
var oDIv=document.querySelector('#test2') console.log(oDIv.classList) oDIv.classList.add("box4") //爲元素增長了類 box4 oDIv.classList.remove("box2") //爲元素刪除了類 box4 oDIv.classList.toggle("box2") //若是元素有box2就刪除box2 若是沒有box2增長box2
JSON.parse("json類型的字符串") 只能解析json類型的字符串轉化爲對象 json必須是一個嚴格的json
嚴格的json 屬性和屬性值都帶着「」
eval("任何字符串") 將任意類型的字符串轉化爲js
var sss=JSON.parse('{"name":"huangxiaojian","age":"23"}') console.log(typeof sss) //object
將js轉化爲字符串
JSON.strify(對象) 返回的是嚴格的json字符串
var sss=JSON.parse('{"name":"huangxiaojian","age":"23"}') console.log(typeof sss) //object var sss1=JSON.stringify(sss); console.log(typeof sss1) //string
對象之間的賦值會出現引用
var a={name:"sasa"}; var b=a; b.name="sa11"; console.log(a.name) //sa11
可是使用for循環對對象的賦值只能是淺拷貝。
實現深拷貝的最簡單的方法。
var a={name:"11"}; var str=JSON.stringify(a); var b=JSON.parse(str); b.name="sasa"; console.log(a.name) //依然爲11
先轉化爲字符串 再將字符串轉化爲對象 實現了深拷貝
html
<div id="test2" class="box1 box2 box3">sasa</div> <div id="miaowei" data-maiaov="妙味" data-maiaov-all="妙味課堂"></div>
js
var maiowei=document.querySelector("#miaowei") console.log(maiowei.dataset.maiaov) //妙味 console.log(maiowei.dataset.maiaovAll) //妙味課堂 使用駝峯式來訪問
在使用自定義的屬性的時候注意:
一、html中屬性值都是 data-name-value=""
二、js中訪問這個值得時候都是 存放在這個元素上的dataset上邊 好比說dataset.nameValue
defer="defer" 延遲加載js這個屬性
<script defer="defer" src="a.js"></script> <script> console.log(333) </script>
會先輸出333載執行a.js文件
異步加載js 加載完就會某個事件
async="async"
異步加載的執行順序是不定的
通常用來加載 和頁面加載和顯示無關的js
改變歷史管理
一、跳轉頁面
二、增長哈希值 http://localhost:63342/study_... onhashchange
三、pushstate()
onhashchange()改變hash值來管理
var oInput=document.getElementById("input1") var div1=document.getElementById("div1"); var json={}; window.onload=function () { oInput.onclick=function () { var number=Math.random(); var arr=randomNum(35,7) json[number]=arr; div1.innerHTML=arr; window.location.hash=number } function randomNum(iAll,isNow) { var arr=[]; var newArr=[]; for(var i=1;i<=iAll;i++){ arr.push(i) } for(var i=0;i<isNow;i++){ newArr.push(arr.splice(Math.ceil(Math.random()*arr.length),1)) } return newArr; } } window.onhashchange=function () { div1.innerHTML=json[window.location.hash.substring(1)]; }
當url部分的哈希值發生變化的時候 div中的值也會發生改變
使用history.push(三個參數) 數據、標題、地址
var oInput=document.getElementById("input1") var div1=document.getElementById("div1"); var json={}; window.onload=function () { oInput.onclick=function () { var arr=randomNum(35,7) history.pushState(arr,'',arr) div1.innerHTML=arr; } window.onpopstate=function (ev) { div1.innerHTML=ev.state } function randomNum(iAll,isNow) { var arr=[]; var newArr=[]; for(var i=1;i<=iAll;i++){ arr.push(i) } for(var i=0;i<isNow;i++){ newArr.push(arr.splice(Math.ceil(Math.random()*arr.length),1)) } return newArr; } }
draggable=true
拖拽元素事件
ondragstart 開始拖拽的時候(而不是鼠標按下)會響應
ondrag 拖拽前和拖拽結束的中間會連續觸發
ondragend 拖拽結束的時候觸發的事件(也就是釋放鼠標的時候)
目標元素(拖拽到的地方)事件
ondragenter 拖拽的元素進入目標區域的時候會響應事件
ondragover 進入目標區域以後離開目標區域以前會一直響應
ondragleave 拖拽的元素離開目標區域的時候會響應事件
ondrop 在目標元素上釋放被拖拽元素的時候會觸發(要想觸發drop事件,就必須觸發在ondragover中阻止默認事件)
html
<ul> <li draggable="true">1</li> <li draggable="true">1</li> <li draggable="true">1</li> </ul> <div id="div1"></div>
js
var lis=document.getElementsByTagName("li"); var i=0; for(var i=0;i<lis.length;i++){ lis[i].ondragstart=function () { this.style.background="red" } lis[i].ondrag=function () { //即便鼠標停下來也會觸發 //console.log(i++) } lis[i].ondragend=function () { this.style.background="green" } } var div1=document.getElementById("div1"); div1.ondragenter=function () { console.log(11) } div1.ondragover=function (e) { //只有在這阻止了默認事件纔會在目標區域釋放的時候 纔會觸發 e.preventDefault(); console.log(i++) } div1.ondragleave=function () { console.log(22) } div1.ondrop=function () { console.log("end") }
剛被拖拽的元素沒有觸發drop時
依次觸發的事件爲:ondragstart ondrag ondragenter ondragover ondragleave ondragend
剛被拖拽的元素會觸發drop時
依次觸發的事件爲:ondragstart ondrag ondragenter ondragover ondrop ondragend
解決火狐下元素的拖放
兼容火狐瀏覽器,而且利用dataTransfer來傳遞數據
html
<ul> <li draggable="true">1</li> <li draggable="true">2</li> <li draggable="true">3</li> </ul> <div id="div1"></div>
var ul=document.getElementsByTagName("ul")[0]; var lis=ul.getElementsByTagName("li"); var i=0; var div1=document.getElementById("div1"); for(var i=0;i<lis.length;i++){ lis[i].index=i; lis[i].ondragstart=function (ev) { //針對火狐瀏覽器實現拖放 而且使用dataTransfer傳遞拖放過程當中的樣式 var ev=ev||window.event; ev.dataTransfer.setData("name",this.index) //改變被拖拽元素被拖到拖拽區域的樣式 ev.dataTransfer.effectAllowed='copy' //進入拖拽區有一個小+ ev.dataTransfer.effectAllowed='link' //進入拖拽區有一個小箭頭 //設置拖拽的樣式 一個DOM元素(包括display:none的元素)也能夠是img,座標 ev.dataTransfer.setDragImage(div1,0,0) //拖拽出來的時候影子就會變爲div1的樣式 this.style.background="red" } lis[i].ondrag=function () { //即便鼠標停下來也會觸發 //console.log(i++) } lis[i].ondragend=function () { this.style.background="green" } } div1.ondragenter=function () { console.log(11) } div1.ondragover=function (e) { //只有在這阻止了默認事件纔會在目標區域釋放的時候 纔會觸發 e.preventDefault(); console.log(i++) } div1.ondragleave=function () { console.log(22) } div1.ondrop=function (ev) { var ss=ul.removeChild(lis[ev.dataTransfer.getData("name")]) div1.appendChild(ss); for(var i=0;i<lis.length;i++){ lis[i].index=i; } }
canvas的默認大小 寬300高150
繪圖的前提
一、獲得畫筆
var oc=document.getElementById("c1");
var oGC=oc.getContext("2d");
二、繪製方塊
oGC.fillRect(50,50,50,50) //L T W H
三、繪製只有邊框的方塊
oGC.strokeRect(50,50,50,50) //L T W H
四、設置繪圖的屬性
oGC.fillStyle="red"; //設置填充的顏色 oGC.strokeStyle="blue" //設置邊框的顏色 oGC.lineWidth=10 //設置邊框的顏色 oGC.lineJoin="round" //矩形四周圓角鏈接 oGC.lineJoin="bevel" //矩形四周斜角鏈接 oGC.lineCap='squre' //方形的頭
五、繪製直線 繪製路徑
oGC.beginPath();
oGC.moveTo(100,100); oGC.lineTo(200,200); oGC.lineTo(300,200); oGC.closePath() //起點和終點進行鏈接 oGC.stroke(); //畫線的功能
六、繪製其餘的路徑
oGC.stroke() 畫線
oGC.fill() 填充
oGC.rect() 填充 默認是黑色
oGC.clearRect(L T W H) 清除畫布的大小
oGC.save() 保存當前的畫筆 在設置畫筆前進行
oGC.restore() 恢復畫筆
window.onload=function () { var oc=document.getElementById("c1"); //獲得繪製環境 var oGC=oc.getContext("2d"); //先將畫筆保存起來 oGC.save(); oGC.fillStyle="red" oGC.beginPath(); oGC.moveTo(50,50); oGC.lineTo(100,50); oGC.lineTo(100,100); oGC.closePath() oGC.fill(); //再恢復畫筆 oGC.restore(); oGC.beginPath(); oGC.moveTo(100,100); oGC.lineTo(200,200); oGC.lineTo(200,300); oGC.closePath(); oGC.fill(); }
canvas畫曲線
畫弧線
oGC.moveTo(100,200)
oGC.arcTo(100,100,200,100,50) //兩組xy 半徑 oGC.stroke()
畫貝塞爾曲線 方法一
oGC.moveTo(100,200)
oGC.quadraticCurveTo(100,100,200,100) //控制點座標 結束點座標 oGC.stroke()
畫貝塞爾曲線 方法二
oGC.moveTo(100,200)
oGC.bezierCurveTo(100,100,200,200,200,100) //第一組控制點 第二組控制點 結束點 oGC.stroke()
canvas的變換
translate 畫布原點的位移 (x,y)
rotate 旋轉的角度(deg) 矩形以左上角的點 旋轉
scale 縮放 (x,y) x和y縮放的比例
在canvas上邊加載圖片
畫筆.drawImage(image,x,y) 參考旋轉圖片的額例子
將圖片平鋪畫布
畫筆.createPattern(obj,"平鋪的方式repeat")
window.onload=function () { var oc=document.getElementById("c1"); //獲得繪製環境 畫筆 var oGC=oc.getContext("2d"); var yImg=new Image(); yImg.src="111.jpg" yImg.onload=function () { draw(); } function draw() { var bg=oGC.createPattern(yImg,'repeat');//獲得的是一個填充的樣式 oGC.fillStyle=bg; oGC.fillRect(0,0,300,300) } }
canvas漸變
線性漸變
var oc=document.getElementById("c1"); //獲得繪製環境 畫筆 var oGC=oc.getContext("2d"); //漸變的起始點的座標 漸變的終點的座標 var obj=oGC.createLinearGradient(150,100,250,200); obj.addColorStop(0,'red') obj.addColorStop(0.5,'green') obj.addColorStop(1,'blue') oGC.fillStyle=obj; oGC.fillRect(150,100,100,100)
放射性漸變
canvas的文本
設置文字的樣式
oGC.font='20px impact' //文字的大小 文字的樣式
設置文字的基線
oGC.textBaseline='top'; bottom
在畫布上寫字
oGC.fillText(str,200,200) // 內容和文字 oGC.strokeText(str,200,200) //內容和文字
設置文字的座標
oGC.textAlign="left" //設置文字的左右基線 oGC.textBaseline='top'; //設置文字的上下基線 oGC.strokeText(str,0,0) //
獲得文字的寬度
oGC.measureText(str).width
爲文字添加陰影
var oc=document.getElementById("c1"); //獲得繪製環境 畫筆 var oGC=oc.getContext("2d"); oGC.font='60px impact' //文字的大小 文字的樣式 var str="sasa" oGC.textAlign="left" oGC.textBaseline='top'; oGC.shadowOffsetX=10; //x軸便宜 oGC.shadowOffsetY=10; //Y軸便宜 oGC.shadowBlur=3 //設置高斯模糊 oGC.shadowColor="red" //設置影音必須的一步 由於默認的陰影顏色是黑色透明 oGC.fillText(str,0,0)
canvas中的像素操做
獲得像素點 畫筆.getImageData(x,y,width,heigth)
爲畫布設置像素點 畫筆.putImageData(像素對象,x,y)
var oc=document.getElementById("c1"); //獲得繪製環境 畫筆 var oGC=oc.getContext("2d"); oGC.fillRect(0,0,100,100); var oImg=oGC.getImageData(0,0,100,100); //獲取到黑色方塊的全部的像素 //oImg爲一個對象 包括 console.log(oImg.width) //寬的像素 console.log(oImg.height) //高的像素 console.log(oImg.data[0]) //40000 總體像素的數組集合 //一個像素點使用四個值表示 rgba for(var i=0;i<oImg.width*oImg.height;i++){ oImg.data[4*i]=255; oImg.data[4*i+1]=0; oImg.data[4*i+2]=0; oImg.data[4*i+3]=100; } //設置新的圖像數據 oGC.putImageData(oImg,100,100) //將oImg添加到100 100的位置
建立新的像素 oGC.createImageData(x,y,w,h)
經過 座標獲得像素點 經過座標設置像素點
//設置像素點 function setXY(obj,x,y,color) { var w=obj.width; var h=obj.height; var d=obj.data; for(var i=0;i<d.length;i++) { d[4*(y*w+x)]=color[0] d[4*(y*w+x)+1]=color[1] d[4*(y*w+x)+2]=color[2] d[4*(y*w+x)+3]=color[3] } } //傳遞imgData x y function getXY(img,x,y) { var color=[]; var w=img.width; var h=img.height; var d=img.data; for(var i=0;i<d.length;i++) { color[0]=d[4*(y*w+x)] color[1]=d[4*(y*w+x)+1] color[2]=d[4*(y*w+x)+2] color[3]=d[4*(y*w+x)+3] } return color }
設置畫筆透明
context.globalAlpha=0.5;
改變合成部分元素的疊加順序 默認的是後畫的會覆蓋以前畫的
源 即將繪製的圖形 目標已經繪製過的圖形
context.gloalCompositionOperation='destination-over' //默認的值
將canvas導出爲圖片
var ii=oc.toDataURL(); //畫布的方法 img.src=ii;
canvas的事件操做
isPointInPath(x,y) 判斷點擊的點是否在路徑內 可是這個方法只會針對最後一個畫的圖形
context.isPointInPath(x,y)
爲每個繪製在每個畫布上的圓添加點擊事件
var oc=document.getElementById("c1"); var img=document.getElementsByTagName("img")[0]; //獲得繪製環境 畫筆 var context=oc.getContext("2d"); var c1=new shape(100,100,50) var c2=new shape(200,200,50) oc.onmousedown=function (ev) { var e=window.event||ev var point={ x:ev.clientX-oc.offsetLeft, y:ev.clientY-oc.offsetTop } c1.repaint(point); c2.repaint(point); } c1.click=function () { console.log(111) } c2.click=function () { console.log(222) } function shape(x,y,r) { this.x=x; this.y=y; this.r=r; context.beginPath(); context.arc(this.x,this.y,this.r,0,360*Math.PI/180); context.closePath(); context.fill(); } shape.prototype.repaint=function (point) { context.beginPath(); context.arc(this.x,this.y,this.r,0,360*Math.PI/180); context.closePath(); context.fill(); if(context.isPointInPath(point.x,point.y)){ this.click(); } }
http://jcscript.com/ 一個專一於操做canvas的庫
同域的不一樣窗口(iframe)之間的通訊、window.open()新打開窗口之間的通訊
一、 iframe 這個頁面就會有兩個窗口
<iframe src="small.html" id="iframe1"></iframe>
找到子窗口
//指向了子窗口的window var smallwindow=iframe1.contentWindow smallwindow.document.body.style.background="red"
二、經過window.open()方法打開的窗口
跨域下會報錯
<input type="button" value="點擊我改變新窗口的窗體顏色" id="btn1"> <iframe src="http://localhost:8888/" id="iframe1"></iframe>
js
var btn1=document.getElementById("btn1"); var iframe1=document.getElementById("iframe1"); btn1.onclick=function () { var window=iframe1.contentWindow console.log(window) window.document.body.style.background="red"; //這就會由於跨域下的限制報錯 }
跨域的方法
一、經過postMeassage window對象的方法
用於這個對象下的方法 給另外的一個窗口發送信息
postMeassage(發送的數據,接收數據的協議+域名) 發送端
window.onMessage(function(){}) 接收端
當接收窗口接受到postmessag方法 發送給過來的消息 就會觸發這個事件
使用postMessage發送的消息
<body> <input type="button" value="點擊我經過postMessage來發送消息" id="btn1"> <iframe src="http://localhost:8888/" id="iframe1"></iframe> </body> <script> var btn1=document.getElementById("btn1"); var iframe1=document.getElementById("iframe1"); btn1.onclick=function () { var window=iframe1.contentWindow window.postMessage('ddasavxv',"http://localhost:8888/") } </script>
服務器端
var http = require('http');//引入http模塊 //開啓服務,監聽8888端口 //端口號最好爲6000以上 var server = http.createServer(function(req,res){ res.writeHeader(200,{ 'content-type' : 'text/html;charset="utf-8"' }); var data; //ev.origin 判斷髮送消息的域 res.write('<div>sasa</div><script>window.onmessage=function (ev) {data=ev.data }</script>');//顯示給客戶端 res.end(); }).listen(8888); console.log('服務器開啓成功');
關於parent
當頁面沒有被其餘頁面包括 這個頁面的額parent就是window
當頁面是<iframe>引入到其餘頁面的時候 此時的parent的時候 就是父頁面的window
top
頂級窗口
二、新版的ajax
html5中的ajax支持跨域
服務器端
app.get("/",function (req,res) { //設置指定的域才能夠跨域訪問這個服務器 res.header("Access-Control-Allow-Origin", "http://localhost:63342"); res.write("sasasasq21sa"); res.end(); })
前端
var btn1=document.getElementById("btn1"); var iframe1=document.getElementById("iframe1"); btn1.onclick=function () { var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function () { if(xhr.readyState==4){ if(xhr.status==200){ console.log(xhr.responseText) } } } xhr.open('get','http://localhost:3000/',true) xhr.send(); }
點擊btn就會在控制檯輸出跨域的服務器輸出的數據
一、爲何須要websocket的存在
由於 HTTP 協議有一個缺陷:通訊只能由客戶端發起。這種單向請求的特色,註定了若是服務器有連續的狀態變化,客戶端要獲知就很是麻煩。咱們只能使用"輪詢":每隔一段時候,就發出一個詢問,瞭解服務器有沒有新的信息。最典型的場景就是聊天室。websocket主要特色就是服務器能夠主動向客戶端推送信息,客戶端也能夠主動向服務器發送信息,是真正的雙向平等對話,屬於服務器推送技術的一種。
二、websocket協議(http協議在同一水平)的特色
(1)創建在 TCP 協議之上,服務器端的實現比較容易。
(2)與 HTTP 協議有着良好的兼容性。默認端口也是80和443,而且握手階段採用 HTTP 協議,所以握手時不容易屏蔽,能經過各類 HTTP 代理服務器。
(3)數據格式比較輕量,性能開銷小,通訊高效。
(4)能夠發送文本,也能夠發送二進制數據。
(5)沒有同源限制,客戶端能夠與任意服務器通訊。
(6)協議標識符是ws(若是加密,則爲wss),服務器網址就是 URL。
使用node搭建websocket
服務器端
var io=require("socket.io"); var socket=io.listen(server); socket.sockets.on('connection',function (socket) { console.log("有人經過socket進來了") //服務器端向客戶端發送事件 hello 信息爲11112121 socket.emit('hello',"歡迎你進來") //服務器接受客戶端發送過來的事件hello11 併發生響應 /* socket.on('hello11',function (data) { console.log(data) })*/ //實現廣播事件 除了他本身收不到其他的人都能收到 socket.broadcast.emit('a','有新人進來了') })
每個socket鏈接都有一個socket實例
客戶端
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script> </head> <body> <div>sasasa</div> <button typeof="button" value="post" id="btn">sasasa</button> <script> window.onload=function () { var oBtn=document.getElementById("btn"); var socket=null; oBtn.onclick=function () { //鏈接器起來的一個socket 實例 var socket=io.connect('http://localhost:8888') //客戶端收到服務器發送的事件hello 作出的響應 socket.on('hello',function (data) { alert(data) //客戶端向服務器發送事件hello11 傳送的數據爲ssjasasjia this.emit('hello11',"ssjasasjia") }) socket.on('a',function (data) { alert(data) }) } } </script>
客戶端就實現了 每次一點擊按鈕就會在你服務器輸出有一我的進來了 進了服務器人,每有一個新人進來就會彈出有新人進來 新人第一次進來的時候只會彈出歡迎你進來
使用node搭建websocket服務器
客戶端
var ws = new WebSocket("ws://localhost:8181"); ws.onopen = function(evt) { console.log("Connection open ..."); ws.send("Hello WebSockets!"); }; ws.onmessage = function(evt) { console.log( "Received Message: " + evt.data); ws.close(); }; ws.onclose = function(evt) { console.log("Connection closed."); };
服務器端
var WebSocketServer = require('ws').Server, wss = new WebSocketServer({ port: 8181 }); wss.on('connection', function (ws) { console.log('client connected'); ws.on('message', function (message) { console.log(message); }); ws.send("sss",function () { console.log(111) }) });
其中新建的wss的屬性有四個值
CONNECTING:值爲0,表示正在鏈接。
OPEN:值爲1,表示鏈接成功,能夠通訊了。
CLOSING:值爲2,表示鏈接正在關閉。
CLOSED:值爲3,表示鏈接已經關閉,或者打開鏈接失敗。
四種狀態的使用以下
var ws = new WebSocket("ws://localhost:8181"); console.log(ws.readyState) //0 CONNECTING:值爲0,表示正在鏈接 ws.onopen = function(evt) { console.log("Connection open ..."); console.log(ws.readyState) //1 OPEN:值爲1,表示鏈接成功,能夠通訊了。 ws.send("Hello WebSockets!"); }; ws.onmessage = function(evt) { console.log( "Received Message: " + evt.data); ws.close(); console.log(ws.readyState) //2 CLOSING:值爲2,表示鏈接正在關閉。 }; ws.onclose = function(evt) { console.log(ws.readyState) //3 CLOSED:值爲3,表示鏈接已經關閉,或者打開鏈接失敗。 console.log("Connection closed."); };
如上websocket的實例對象還有以下的方法
webSocket.onopen 用於指定鏈接成功後的回調函數。
webSocket.onclose 用於指定鏈接關閉後的回調函數。
webSocket.onmessage 用於指定收到服務器數據後的回調函數。
webSocket.send 用於向服務器發送數據。
離線存儲的好處
沒有網絡的時候能夠正常訪問
快速構建相應頁面 沒必要再使用http佔用資源帶寬
緩存的能夠是任何文件
搭建離線應用
一、服務器端設置頭信息
二、html標籤加上 manifest="demo.manifest"
三、寫demo.manifest清單
CACHE MANIFEST
../22.jpg
/logo.gif
/main.js
js的單線程變爲多線程 使用new Worker(test.js) 在test.js文件裏邊處理數據處理完以後 再返回
在test.js文件裏邊的運行環境和普通的環境不同 有以下的規定
一、navgator :appName、appVersion、userAgent、platform
二、location 全部屬性都是隻讀的
三、self 指向全局的worker對象
四、全部的ECMA 對象Object Array Date等
五、XMLHttpRequest構造器
六、setTimeout和setInterval方法
七、close()方法 馬上中止worker運行 已經使用完webworks
八、importScripts方法 引入在這個運行環境裏邊須要的其餘js文件
因此這個運行環境只容許 對經過pastMessage傳遞過來的數據 作處理 處理完之後再經過postmessage傳回來計算後的數據
使用方法
主線程
<script> var ss=new Worker("test.js"); ss.postMessage(12) ss.onmessage=function (p1) { console.log(p1.data) } //13 </script>
後臺線程
var dd; self.onmessage=function (p1) { dd=p1.data; self.postMessage(++dd) }
實現任何內容均可以編輯 增長屬性 contenteditable="true"
<div contenteditable="true">sasa</div>
雙擊就能夠編輯
實現語音輸入
<input type="text" x-webkit-speech lang="zh-CN"/>
桌面提醒 網頁版微信提醒
navigator.geolocation獲得地理信息的座標
第一個方法一次請求
window.onload=function () { var text=document.getElementById("text"); var btn=document.getElementById("btn"); btn.onclick=function () { navigator.geolocation.getCurrentPosition(function (position) { console.log(position) text.value+='經度'+position.coords.longitude+'\n' //獲得經度 text.value+='緯度'+position.coords.latitude+'\n' //獲得經度 text.value+='準確度'+position.coords.accuracy+'\n' //獲得經度 text.value+='海拔'+position.coords.altitude+'\n' //獲得經度 text.value+='海拔準確度'+position.coords.altitudeAccuracy+'\n' //獲得經度 text.value+='進行方向'+position.coords.heading+'\n' //獲得經度 text.value+='地面速度'+position.coords.speed+'\n' //獲得經度 text.value+='事件戳'+position.coords.timeStamp+'\n' //獲得經度 },function (error) { //地理位置獲取失敗 },{ //配置的選項 enableHighAcuracy:true, //高準確的 timeout:5000 //請求限制的事件 }) } }
<input type="button" id="btn" value="點擊"> <br> <textarea style="width: 300px;height:300px;" id="text"></textarea>
實現了點擊一次就能夠 獲取一次當前的地理位置
第二個方法 連續請求位置信息 適合移動設備 動的時候會自動觸發
window.onload=function () { var text=document.getElementById("text"); var btn=document.getElementById("btn"); btn.onclick=function () { var timer= navigator.geolocation.watchPosition(function (position) { console.log(position) text.value+='經度'+position.coords.longitude+'\n' //獲得經度 text.value+='緯度'+position.coords.latitude+'\n' //獲得經度 text.value+='準確度'+position.coords.accuracy+'\n' //獲得經度 text.value+='海拔'+position.coords.altitude+'\n' //獲得經度 text.value+='海拔準確度'+position.coords.altitudeAccuracy+'\n' //獲得經度 text.value+='進行方向'+position.coords.heading+'\n' //獲得經度 text.value+='地面速度'+position.coords.speed+'\n' //獲得經度 text.value+='事件戳'+position.coords.timeStamp+'\n' //獲得經度 },function (error) { //地理位置獲取失敗 //清除定時器 navigator.geolocation.clearWatch(time) },{ enableHighAcuracy:true, //高準確的 timeout:5000 //請求限制的事件 能夠配置更新的頻率 }) } }
cookie存儲特色
一、存儲限制
二、客戶端 服務器端 都會請求服務器
三、頁面之間cookie是共享的
storage存儲的特色
sessionstorage 臨時會話頁面打開到關閉的時間段 頁面之間是不會共享的哪怕是在一個域名下
LocalStorage 永久存儲 必須手動刪除 頁面之間是能夠共享的
存儲5M
客戶端完成,不會請求服務器處理
sessionStorage數據是在頁面之間是不共享的、localStorage頁面之間能夠共享數據 即便瀏覽器關閉數據也還在 除非用主動刪除數據
本地存儲的方法
sessionStorage.setItem(key,value) 設置key和value sessionStorage.getItem(key) 獲得value
sessionStorage.removeItem(key)刪除key對應的值 sessionStorage.clear() 刪除所有的數據
本地存儲的事件
window.addEventListener('storage',function(){})
可是這個事件不會在對數據進行改變的窗口上觸發 在本頁面上觸發不了 可是在其餘的共享頁面上能夠觸發
window.addEventListener('storage',function ( ev) { console.log(ev.key) console.log(ev.newValue) console.log(ev.oldValue) console.log(ev.storageArea) console.log(ev.url) },false)
實例同步購物車
window.onload=function () { var aInput=document.getElementsByTagName('input'); for(var i=0;i<aInput.length;i++){ aInput[i].onclick=function () { if(this.value){ window.localStorage.setItem('sel',this.value); }else{ window.localStorage.setItem('onsel',this.value); } } } window.addEventListener('storage',function (ev) { console.log(ev.key) for(var i=0;i<aInput.length;i++){ if(ev.key=='sel'){ for(var i=0;i<aInput.length;i++){ if(ev.newValue==aInput[i].value){ aInput[i].checked=true; } } }else if(ev.key=='onsel'){ for(var i=0;i<aInput.length;i++){ if(ev.newValue==aInput[i].value){ aInput[i].checked=false; } } } } },false) }
用戶在選擇完商品的時候 共享的頁面也會同步的更新
audio video
兩個標籤的
src屬性執行播放源
controls屬性顯示
autoplay屬性控制自動播放
loop媒體是否循環播放
currenTime從開始到播放如今所用的時間 不只能夠讀取 還能夠設置
duration 媒體的總時間 是可讀的
volume 0.0-1.0 音量的相對值
muted 是不是靜音的狀態
autobuffer 開始的時候 是否緩存加載
媒體元素的只讀屬性
paused 媒體是否正在暫停
ended 媒體是否播放結束
媒體元素的方法
play() 讓媒體元素開始播放
pause() 讓媒體元素暫停播放
load() 從新加載媒體 當媒體的源改變的額時候 必須使用這個方法才能在媒體元素上生效
媒體元素的事件
loadstart 開始加載的時候會觸發
end 播放結束的時候會觸發
video獨有的屬性poster 視頻播放的預覽圖片width 視頻播放界面的寬度 height 能夠設置能夠讀取videoWidth 視頻實際的寬 利用 source標籤 實現各個瀏覽器的播放兼容 這個標籤是audio或者video的子標籤