html5
一、属性篇
1、placeholder 提示信息
<input type="text" placeholder="请输入用户名">
2、input的新type
(1)Calendar类中的date,time,week,datetine-local
<!-- Calendar类 -->
<input type="date"> 兼容型差,基本只有chrome支持
<input type="time">
<input type="week">
<input type="datetime-local">
(2)number:只能输入数字,可以设置最大最小值以及步长
<input type="number" min="1" max="10" step="1">兼容型差,基本只有chrome支持
(3)email:提交表单时,进行邮箱验证
<input type="email">兼容型差,基本只有chrome,firefox支持
(4)color:可以选择颜色值
<input type="color">兼容型差,基本只有chrome支持
(5)range:一个滑动条,可以设置最大最小值以及步长
<input type="range" min="1" max="100" step="2">
(6)search:搜索域,可以记录搜索过的内容
<input type="search">兼容型差,基本只有chrome支持
(7)url:在提交表单时,会自动验证 url 域的值。
<input type="url"> 兼容chrome或firefox和opera
大多数浏览器都不兼容,故大部分用不到,附带W3school兼容性一览,不过有些不准
3、datalist:规定输入域的选项列表。
解释:列表是通过 datalist 内的 option 元素创建的。如需把 datalist 绑定到输入域,请用输入域的 list 属性引用 datalist 的 id。兼容性差,基本只有谷歌支持
请选择输入网址:
<input type="url" list="url_list" name="link" />
<datalist id="url_list">
<option label="bilibili" value="https://www.bilibili.com" />
<option label="baidu" value="http://www.baidu.com" />
<option label="csdn" value="https://www.csdn.net" />
</datalist>
4、contentEditable:内容可编辑
**解释:**无兼容性问题,常用作修改表格,该属性是可以被子元素继承
<div contenteditable="true">
我终于可以修改了!
<br>
<span>也可以修改我哦,因为我继承了父类的</span>
<br>
<span contenteditable="false">你修改不了我的</span>
</div>
<!--
注意:设置contenteditable="false"的span标签可以被整体删除
因为span标签是在div里面的,可以把整个span标签删除
-->
5、draggable:规定元素是否可拖动。
(1)draggable=“true”
注意:默认是false,但是a
和img
标签默认是可以拖拽的。只有chrome和safari可以正常使用。
<div class="box" draggable="true"></div>
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 100px;
height: 100px;
background-color: #f0f;
}
</style>
(2)拖拽的生命周期
当鼠标按下的一瞬间,拖拽开始
当鼠标按下一直移动,拖拽进行中
当鼠标松开的一瞬间,拖拽结束
拖拽分为两块:被拖拽的物体以及目标区域
(3)被拖拽的物体上的事件:ondragstart,ondrag,ondragend
<script>
var oDrag = document.getElementsByClassName("box")[0]
oDrag.ondragstart = function(e){
//开始事件 按下元素一瞬间不会触发,稍微移动一下才会触发
console.log(e)
//改变鼠标的样式 兼容性极差
e.dataTransfer.effectAllowed = "link"
}
oDrag.ondrag = function(e){
//移动事件 移动的瞬间开始触发
console.log(e)
}
oDrag.ondragend = function(e){
// 结束事件 松开鼠标一瞬间触发
console.log(e)
// clientX和clientY是移动的点的像素
}
</script>
案例:拖拽
<div class="box" draggable="true"></div>
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 100px;
height: 100px;
background-color: #f0f;
position: absolute;
}
</style>
<script>
var oDrag = document.getElementsByClassName("box")[0]
var startX = 0;
var startY = 0
oDrag.ondragstart = function(e){
startX = e.clientX;
startY = e.clientY;
}
oDrag.ondragend = function(e){
var x = e.clientX - startX
var y = e.clientY - startY
oDrag.style.left = oDrag.offsetLeft + x +"px";
oDrag.style.top = oDrag.offsetTop + y +"px";
}
</script>
(4)目标区域上的事件:ondragenter,ondragover,ondragleave,ondrop
<div class="box" draggable="true"></div>
<div class="target"></div>
<script>
var targetDiv = document.getElementsByClassName("target")[0]
targetDiv.ondragenter = function(e){
// 并不是元素图形进入目标区域触发,而是拖拽的鼠标进入目标区域触发
console.log(e)
}
targetDiv.ondragover = function(e){
// 鼠标进入目标区域时不停触发
console.log(e)
// e.preventDefault();
}
targetDiv.ondragleave = function(e){
// 离开目标区域触发
console.log(e)
}
targetDiv.ondrop = function(e){
// 当鼠标在目标区域松开时 想要在目标区域用ondrop,需要取消ondragover的默认事件
// 所有标签元素,当拖拽周期结束时,默认事件时是回到原处
// 事件是由行为触发的,但是一个行为可以不止触发一个事件
// ondrapover --> 回到原处 --> 执行drop
console.log(e)
//改变鼠标的样式 兼容性极差仅ondrop中有
e.dataTransfer.dropEffect = "link"
}
</script>
拖拽案例
<style>
*{
padding: 0;
margin: 0;
}
.box1{
width: 200px;
height: 200px;
border: 1px solid black;
position: absolute;
}
.box2{
width: 200px;
height: 200px;
border: 1px solid black;
position: absolute;
left: 300px;
}
li{
position: relative;
display: block;
width: 50px;
height: 40px;
background-color: #0ff;
margin: 10px auto;
}
</style>
<div class="box1">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="box2"></div>
<script>
var dragDom = null;
var liList = document.getElementsByTagName("li")
for(var i=0;i<liList.length;i++){
liList[i].setAttribute("draggable",true)
liList[i].ondragstart = function(e){
dragDom = e.target
}
}
var box1 = document.getElementsByClassName("box1")[0]
box1.ondragover = function(e){
e.preventDefault();
}
box1.ondrop = function(e){
box1.appendChild(dragDom)
}
var box2 = document.getElementsByClassName("box2")[0]
box2.ondragover = function(e){
e.preventDefault();
}
box2.ondrop = function(e){
box2.appendChild(dragDom)
}
</script>
6、hidden:隐藏
<p hidden>这个段落应该被隐藏。</p>
7、data-val: 自定义数据
data-* 属性用于存储页面或应用程序的私有自定义数据。
<ul>
<li data-animal-type="鸟类">喜鹊</li>
<li data-animal-type="鱼类">金枪鱼</li>
<li data-animal-type="蜘蛛">蝇虎</li>
</ul>
案例:
<h1>物种分类</h1>
<ul>
<li onclick="showDetails(this)" id="owl" data-animal-type="鸟类">喜鹊</li>
<li onclick="showDetails(this)" id="salmon" data-animal-type="鱼类">金枪鱼</li>
<li onclick="showDetails(this)" id="tarantula" data-animal-type="蜘蛛">蝇虎</li>
</ul>
<script>
function showDetails(animal) {
var animalType = animal.getAttribute("data-animal-type");
alert(animal.innerHTML + "是一种" + animalType + "。");
}
</script>
二、标签篇
1、语义化标签
<!-- 本质都是div只不过是名字不同 -->
<header></header>
<footer></footer>
<nav></nav> <!-- 导航栏 -->
<article></article> <!-- 文章,可以被直接引用 -->
<section></section> <!-- 段落 -->
<aside></aside><!-- 侧边栏,几乎不用 -->
2、canvas(画板)
暂不介绍,后续更新
3、svg(画板)
暂不介绍,后续更新
4、audio(声音播放)
与video相同,请比照video属性进行学习。
5、video(视频播放)
(1)支持的音频格式:.ogg
、.mp4
、.webm
兼容问题,可以写多个源地址,根据顺序依次判断
<video width="320" height="240" controls="controls">
<source src="movie.ogg" type="video/ogg">
<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
(2)controls:供添加播放、暂停和音量控件。
<video src="movie.ogg" controls></video>
(3)autoplay:视频在就绪后立马播放
<video src="movie.ogg" controls autoplay></video>
(4)loop:循环播放
<video src="movie.ogg" controls loop></video>
(5)preload:在页面加载时加载视频
解释:如果使用 “autoplay”,则忽略该属性。Chrome:preload默认值为auto,加载部分视频;
auto:当页面加载后载入整个视频
meta :当页面加载后只载入元数据,比如长度等等
none :当页面加载后不载入视频,认为用户不需要看,减少性能
<video src="movie.ogg" preload="load"/>
Video + DOM
注释:在所有属性中,只有 videoWidth 和 videoHeight 属性是立即可用的。在视频的元数据已加载后,其他属性才可用。
在谷歌浏览器中,以下演示在控制台中进行或写点击事件触发使用,否则会报错。是因为谷歌浏览器自动播放的政策导致的。(autoplay政策,为了避免标签产生随机噪音禁止没有交互前使用js进行播放)
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
以下演示用的的html
<video src="love.mp4" controls></video>
(1)play() 开始,pause() 暂停
var video = document.getElementsByTagName("video")[0]
video.play()
video.pause()
(2)load():方法重新加载音频/视频元素。
video.load()
(3)currentTime和duration
currentTime: 设置或返回音频/视频中的当前播放位置(以秒计)
duration:返回当前音频/视频的长度(以秒计)
console.log("当前播放时间:"+video.currentTime)
console.log("总时长:"+video.duration)
video.currentTime = 1
(4)volume:当前音量
解释:音量大小在0-1之间
video.volume = 1
(5)paused:返回当前时暂停还是播放
video.paused
(6)playbackRate:播放倍速
video.playbackRate=0.5
(7)oncanplay:事件,当浏览器可以播放音频/视频时触发
video.oncanplay=function(){
alert("Can start playing video")
};
注释:在所有属性中,只有 videoWidth 和 videoHeight 属性是立即可用的。在视频的元数据已加载后,其他属性才可用。
案例:自己的音频播放器
html部分
<div class="video_player">
<video class="video" src="./love.mp4"></video>
<div class="menu">
<div class="play">播放</div>
<div class="time">0.00/0.00</div>
<div class="progress_bar">
<div></div>
<i></i>
</div>
<div class="quick">倍速</div>
<div class="quick_list">
<ul>
<li>x1</li>
<li>x1.25</li>
<li>x1.5</li>
<li>x2</li>
</ul>
</div>
<div class="volumeAdd">音量+</div>
<div class="volumeDe">音量-</div>
</div>
</div>
css部分
<style>
*{
padding: 0;
margin: 0;
}
.video_player{
width: 1000px;
height: 500px;
position: relative;
margin: 0 auto;
}
.video{
width: 1000px;
height: 500px;
position: absolute;
left: 0;
top: 0;
}
.menu{
position: absolute;
width: 100%;
height: 50px;
left: 0;
bottom: 0;
background-color: rgba(0, 0, 0, .5);
}
.play{
width: 60px;
height: 30px;
position: absolute;
top: calc(50% - 15px);
margin-left: 20px;
border-radius: 5px;
border: 1px solid #fff;
color: #fff;
line-height: 30px;
text-align: center;
cursor: pointer;
}
.time{
width: 120px;
height: 30px;
position: absolute;
top: calc(50% - 15px);
margin-left: 100px;
color: #fff;
line-height: 30px;
text-align: center;
cursor: pointer;
}
.progress_bar{
position: absolute;
width: 100%;
height: 2px;
left: 0px;
background-color: #ccc;
top: -2px;
}
.progress_bar div{
position: absolute;
width: 120px;
height: 2px;
top: 0;
left: 0;
background-color: orange;
}
.progress_bar i{
display: block;
position: absolute;
width: 6px;
height: 6px;
border-radius: 50%;
background-color: #fff;
left: 120px;
top: -2px;
}
.quick{
width: 60px;
height: 30px;
position: absolute;
top: calc(50% - 15px);
right: 100px;
border-radius: 5px;
border: 1px solid #fff;
color: #fff;
line-height: 30px;
text-align: center;
cursor: pointer;
}
.quick_list{
width: 60px;
height: 80px;
position: absolute;
bottom: 70px;
right: 100px;
border-radius: 5px;
color: #fff;
text-align: center;
cursor: pointer;
padding: 5px 0;
}
.quick_list{
display: none;
}
.quick_list ul{
list-style: none;
}
.quick_list ul li {
height: 20px;
margin: 4px 0;
}
.quick_list ul li:hover {
color: #f40;
}
.volumeAdd,.volumeDe{
width: 60px;
height: 30px;
position: absolute;
top: calc(50% - 15px);
border-radius: 5px;
border: 1px solid #fff;
color: #fff;
line-height: 30px;
text-align: center;
cursor: pointer;
}
.volumeAdd{
left: 300px;
}
.volumeDe{
left: 380px;
}
</style>
js部分
<script>
var videoPlayer = document.getElementsByClassName("video_player")[0]
var video =videoPlayer.getElementsByTagName("video")[0]
var menu = document.getElementsByClassName("menu")[0]
var play = document.getElementsByClassName("play")[0]
var time = document.getElementsByClassName("time")[0]
var progress_bar = document.getElementsByClassName("progress_bar")[0]
var quick_list = document.getElementsByClassName("quick_list")[0]
var quick = document.getElementsByClassName("quick")[0]
var volumeAdd = document.getElementsByClassName("volumeAdd")[0]
var volumeDe = document.getElementsByClassName("volumeDe")[0]
videoPlayer.onmouseenter = function(){
menu.style.display = "block"
}
videoPlayer.onmouseleave = function(){
menu.style.display = "none"
}
play.onclick = function(){
if(video.paused){
video.play()
play.innerHTML = "暂停"
}else{
video.pause()
play.innerHTML = "播放"
}
}
progress_bar.onmouseenter = function(){
progress_bar.style.height = "14px"
progress_bar.style.top = "-14px"
progress_bar.getElementsByTagName("div")[0].style.height = "14px"
progress_bar.getElementsByTagName("i")[0].style.height = "18px"
}
progress_bar.onmouseleave = function(){
progress_bar.style.height = "2px"
progress_bar.style.top = "-2px"
progress_bar.getElementsByTagName("div")[0].style.height = "2px"
progress_bar.getElementsByTagName("i")[0].style.height = "6px"
}
progress_bar.onclick = function(e){
var x = e.layerX
var total = progress_bar.clientWidth
var time = x / total * video.duration
video.currentTime = time
// 想要设置时间跳转请求信息中必须有Content-Range或者Range: bytes 262144-1393631/1393632属性
}
quick.onclick = function(){
quick_list.style.display = "block"
}
quick_list.onmouseleave = function(){
this.style.display = "none"
}
var liList = quick_list.getElementsByTagName("li")
for(var i = 0;i<liList.length;i++){
liList[i].index = i
liList[i].onclick = function(){
if(this.index == 0){
video.playbackRate = 1
quick.innerHTML = "倍速"
}else if(this.index == 1){//1.25
video.playbackRate = 1.25
quick.innerHTML = "x1.25"
}else if(this.index == 2){//1.5
video.playbackRate = 1.5
quick.innerHTML = "x1.5"
}else{
video.playbackRate = 2
quick.innerHTML = "x2"
}
}
}
volumeAdd.onclick = function(){
video.volume = video.volume + 0.1>=1?1:video.volume + 0.1
}
volumeDe.onclick = function(){
video.volume = video.volume - 0.1<=0?0:video.volume - 0.1
}
setInterval(() => {
var total = video.duration
var nowTime = video.currentTime
time.innerHTML = parseInt(nowTime/60)+":"+parseInt(nowTime%60)+"/"+
parseInt(total/60)+":" + parseInt(total%60)
var progressWidth = nowTime / total * progress_bar.clientWidth
progress_bar.getElementsByTagName("div")[0].style.width = progressWidth +"px"
progress_bar.getElementsByTagName("i")[0].style.left = progressWidth +"px"
}, 1000);
</script>
三、API篇
1、Geolocation:地理定位
geLocation:获取地理信息(一些系统不支持)
1.GPS 台式机几乎没有GPS,笔记本大多数没有GPS,智能手机基本都有GPS
2.网络(根据基站)只能粗略估计地理位置
3.https协议和文件协议可以获取,http协议因为安全问题不可以获取
// 经度最大180°,维度最大90°
window.navigator.geolocation.getCurrentPosition(
function(position){
console.log(position)
},function(err){
console.log(err)
}
)
err错误代码:
Permission denied - 用户不允许地理定位
Position unavailable - 无法获取当前位置
Timeout - 操作超时
返回的position对象:
coords.latitude -十进制数的纬度
coords.longitude -十进制数的经度
coords.accuracy -位置精度
coords.altitude -海拔,海平面以上以米计
coords.altitudeAccuracy -位置的海拔精度
coords.heading -方向,从正北开始以度计
coords.speed -速度,以米/每秒计
timestamp -响应的日期/时间
2、requestAnimationFrame:动画优化
注意:若你想在浏览器下次重绘之前继续更新下一帧动画,那么回调函数自身必须再次调用window.requestAnimationFrame()
window.requestAnimationFrame(callback);
参数:
callback
下一次重绘之前更新动画帧所调用的函数(即上面所说的回调函数)。它表示requestAnimationFrame() 开始去执行回调函数的时刻。
返回值:
一个 long 整数,请求 ID ,是回调列表中唯一的标识。是个非零值,没别的意义。你可以传这个值给 window.cancelAnimationFrame() 以取消回调函数。
(1)用setInterval
function move(){
var box = document.getElementsByClassName("box")[0]
if(box.offsetLeft>700){
clearTimeout(timer)
}
box.style.left = box.offsetLeft +20 +"px"
}
var timer = setInterval(move,1000/60)
move()
(2)用requestAnimationFrame()
var timer = null
function move(){
var box = document.getElementsByClassName("box")[0]
if(box.offsetLeft>700){
cancelAnimationFrame(timer)
}else{
timer = requestAnimationFrame(move)
box.style.left = box.offsetLeft +20 +"px"
}
}
move()
对比用setInterval和requestAnimationFrame效果
因为requestAnimationFrame是每秒60帧,每一帧的执行时间要少于1/60 该方法上有一个执行队列,可以准确的执行每一帧
setInterval 可能不会是一秒60帧,执行队列时间可能多余1秒
注:cancelAnimationFrame相当于clearTimeOut
为了更好的兼容cancelAnimationFrame和requestAnimationFrame,我们自己写一个兼容
window.cancelAnimationFrame = (function(){
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
function(id){
window.clearInterval(id)
}
})()
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(id){
window.setInterval(id,1000/60)
}
})()
3、localStorage和sessionStorage
localStorage:没有时间限制的数据存储
sessionStorage:针对一个 session 的数据存储
(1)localStroage
赋值:只能存字符串
//localStorage赋值两种方式
localStorage.name = "lkx"
localStorage.arr = JSON.stringify([1,2,3])
localStorage.setItem("name","lkx")
取值:
//获取localStorage的两种方式
console.log(JSON.parse(localStorage.arr))
console.log(JSON.parse(localStorage.getItem("arr")))
删除:
//删除localStorage
localStorage.removeItem("arr")
(2)sessionStorage
赋值:
sessionStorage.name = "lkx"
sessionStorage.arr = JSON.stringify([1,2,3])
sessionStorage.setItem("name","lkx")
取值:
console.log(sessionStorage.name)
console.log(sessionStorage.getItem("name"))
删除:
sessionStorage.removeItem("name")
因为二者只能存字符串
// 只存字符串 --> JSON 方法来转换
localStorage.obj = JSON.stringify({name:"lkx",age:"18"})
console.log(JSON.parse(localStorage.obj))
localStorage和sessionStorage选用
1.长期放在浏览器内的,写入localStorage(无论窗口是否关闭)
2.这次会话临时需要存储的变量,每次浏览器关闭,sessionStorage都会自动清空
localStorage 和 cookie 区别
1.localStorage在发送请求的时候不会把数据发出去,而cookie会
2.cookie存储的内容比较少4k,localStrage可以存放5M
4、history
(1)pushState(state,title,url):添加和修改历史记录条目
参数:
state:状态对象,state是一个JavaScript对象,通过pushState () 创建新的历史记录条目。无论什么时候用户导航到新的状态,popstate事件就会被触发,且该事件的state属性包含该历史记录条目状态对象的副本。
title:标题,不兼容,目前忽略这个参数,但未来可能会用到。
url:该参数定义了新的历史URL记录。
在某种意义上,调用 pushState()
与 设置 window.location = "#foo"
类似,二者都会在当前页面创建并激活新的历史记录。但 pushState()
具有如下几条优点:
- 新的 URL 可以是与当前URL同源的任意URL 。相反,只有在修改哈希时,设置
window.location
才能是同一个document
。 - 如果你不想改URL,就不用改。相反,设置
window.location = "#foo";
在当前哈希不是#foo
时, 才能创建新的历史记录项。 - 你可以将任意数据和新的历史记录项相关联。而基于哈希的方式,要把所有相关数据编码为短字符串。
- 如果
标题
随后还会被浏览器所用到,那么这个数据是可以被使用的(哈希则不是)。
注意: pushState()
绝对不会触发 hashchange
事件,即使新的URL与旧的URL仅哈希不同也是如此。
history.pushState({inpVal:"foo"},null,"/foo")
(2)popstate: 每当活动的历史记录项发生变化时触发
如果当前活动的历史记录项是被 pushState 创建的,或者是由 replaceState 改变的,那么 popstate 事件的状态属性 state 会包含一个当前历史记录状态对象的拷贝。
window.addEventListener("popstate",function(e){
console.log(e)
})
(3)hashchange:哈希值改变时触发
window.addEventListener("hashchange",function(e){
console.log(e)
})
案例:记录搜索内容
<input type="text" id="search"><button οnclick="search()">搜索</button>
<div class="box"></div>
<script>
var data = [
{name:"html"},
{name:"css"},
{name:"js"},
{name:"python"},
{name:"java"},
{name:"c"}]
function search(){
var value = document.getElementById("search").value
var result = data.filter(function(obj){
if(obj.name.indexOf(value)>-1){
return obj
}
})
render(result)
/*@params
state:一个与指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数。如果不需要这个对象,此处可以填null。
title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null。
url:新的网址,必须与当前页面处在同一个域。
url中包含# 修改hash --> history.hash
/ 不会修改hash
*/
history.pushState({inpVal:value},null,"#"+value)
// history.pushState({inpVal:value},null,"/"+value)
}
function render(data) {
var content = ""
for(var i=0;i<data.length;i++){
content += `<div> ${data[i].name} </div>`
}
document.getElementsByClassName("box")[0].innerHTML = content
}
//只要url变了就会变化
window.addEventListener("popstate",function(e){
console.log(e)
document.getElementById("search").value = e.state.inpVal
var value = e.state.inpVal
var result = data.filter(function(obj){
if(obj.name.indexOf(value)>-1){
return obj
}
})
render(result)
})
//hash值变了才会触发,锚点变了才会触发 #
window.addEventListener("hashchange",function(e){
console.log(e)
})
</script>
<script>
render(data)
</script>
5、Node + webpack 四行写个服务器
解释:因为下面几个属性需要在服务器中运行,所以用express写个简单的服务器
var express = require("express")
var app = new express()
//默认监听index.html文件
app.use(express.static("./webpage"))//监听哪个文件夹的静态文件
app.listen(3000)//监听哪个端口号
6、deviceorientation:设备旋转方向
注:只有带有陀螺仪的设备才支持体感。苹果设备的页面只有在 http协议的情况下 才能使用这些接口
属性值:
alpha:指北 [0,360) 0:北
beta:平放的时候 beta值为0 立起的时候(短边接触桌面直立) beta 90
gamma:平方的时候 gamma值为0 立起来的时候(长边接触桌面的直立) gamma 90
演示:在手机上访问。将该html文件放在服务器所监听的文件夹下,通过手机端访问ip地址+端口号+文件名。(手机和笔记本要在同一个局域网内)
window.addEventListener("deviceorientation",function(e){
var box = document.getElementsByClassName("box")[0]
box.innerHTML = `alpha:${e.alpha} </br> beta:${e.beta} </br>gamma:${e.gamma} </br>`
});
7、devicemotion:设备运动/手势
属性值:
accelerationIncludingGravity:重力加速度(包括重心引力9.8)
acceleration(x,y,z):加速度(需要设备陀螺仪支持)
rotationRate(alpha,beat,gamma):旋转速度
interval:获取的时间间隔
演示:在手机上访问。将该html文件放在服务器所监听的文件夹下,通过手机端访问ip地址+端口号+文件名。(手机和笔记本要在同一个局域网内)
window.addEventListener("devicemotion",function(e){
var box = document.getElementsByClassName("box")[0]
box.innerHTML = `x:${e.acceleration.x} </br> y:${e.acceleration.y} </br>z:${e.acceleration.z} </br>`
if(Math.abs(e.acceleration.x) > 10 ||Math.abs(e.acceleration.y) > 10||Math.abs(e.acceleration.z) > 10){
box.style.color = "red"
}
});
8、Worker:多线程
解释:js都是单线程的。worker是多线程的但是不能操作dom,没有window对象,不能读取本地件,可以发ajax ,可以进行计算
注:不能file方式打开(本地存储文件),只能在服务器中使用
(1)创建Worker对象
//会运行worker.js中的代码
var worker = new Worker("./worker.js");
(2)发送和接受数据:onmessage事件中的event.data
发送数据:
worker.postMessage({num:10000})
接受数据:
//当worker发送数据时,就会onmessage就会监听到
//事件源e中的data属性中含有发送的数据
worker.onmessage = function(e){
console.log(e.data)
}
(3)执行时间比较
无worker时:执行时间时47ms(笔记本性能不同,时间有出入)
var startTime = Date.now()
console.log("========")
console.log("========")
var a = 1000000
var result=0
for(var i=0;i<a;i++){
result+=i
}
console.log(result)
console.log("========")
console.log("========")
var endTime = Date.now()
console.log(endTime-startTime)
使用worker计算时:执行时间3ms(笔记本性能不同,时间有出入)
index.js
var startTime = Date.now()
console.log("========")
console.log("========")
var a = 1000000
var worker = new Worker("./worker.js");
worker.postMessage({num:a})
worker.onmessage = function(e){
console.log(e.data)
}
console.log("========")
console.log("========")
var endTime = Date.now()
console.log(endTime-startTime)
worker.js
this.onmessage = function(e){
var result=0
for(var i=0;i<e.data.num;i++){
result+=i
}
this.postMessage(result)
}
(4)导入其他js文件,执行运算方法
//index.js
var worker = new Worker("./worker.js");
worker.postMessage({num:10000})
//worker.js
importScripts("./math.js")
this.onmessage = function(e){
console.log(e.data)
console.log(this.getSum(1,3))
}
//math.js
function getSum(a,b){
return a + b
}