https://developer.mozilla.org/zh-CN/docs/Web/JavaScript
1. js组成 1.1. javascript语法 ECMScript 由ECMA国际(原欧洲计算机制造商协会)进行标准化的一门编程语言,这种语言在万维网上应用广泛,往往被称为JavaScript(网景公司)或JScript(微软公司),但实际上后两者是ECMAScript语言的实现和扩展
ECMAScript规定了JS的编程语法和基础核心只是,是所有浏览器共同蹲守的一套js语法工业标准
1.2. 页面文档对象模型 DOM Document Object Model,是w3c组织推荐的处理可扩展标记语言的标准编程接口
通过DOM提供的接口可以对页面上的各种元素进行操作(大小,颜色,位置等)
1.3. 浏览器对象模型 BOM Browser Object Model,浏览器对象模型,提供了独立于内容的,可以与浏览器窗口进行互动的对象结构
通过BOM可以操作浏览器窗口,比如弹出框,控制浏览器跳转,获取分辨率等
2. js书写位置 2.1. 行内式 1 2 3 <body > <input type ="button" value ="点击一下" onclick ="alert('Hello World')" > </body >
2.2. 内嵌式 1 2 3 4 5 <head > <script > alert ('Hello World' ); </script > </head >
2.3. 外文件 1 <script src ="" > </script >
3. 输入输出语句
方法
说明
归属
alert(msg)
浏览器弹出警示框
浏览器
console.log(msg)
浏览器控制台打印输出信息
浏览器
prompt(info)
浏览器弹出输入框,用户可以输入
浏览器
4. 变量 4.1. 声明变量
var
是js关键字,用来声明变量。计算机自动为变量分配内存空间
age
变量名,通过变量名访问内存中分配的变量空间
4.2. 赋值
5. 数据类型 5.1. 数字型 1 2 3 4 alert (Number .MAX_VALUE );alert (Number .MIN_VALUE );
5.2. 字符串型 引号可以是双引号或单引号
引号嵌套
外双内单/外单内双
1 var strMsg = 'Hello "World"' ;
5.3. typeof检测变量数据类型 1 2 3 var num=10 ;console .log (typeof num);
5.4. 数据类型转换 5.4.1. 转为字符串
方式
用法
toString()
num.toString()
String()
String(num)
+
num+””
5.4.2. 转为数字
方式
用法
parseInt(string)
parseInt(‘78’)
parseFloat(string)
parseFloat(‘78.21’)
Number(string)
Number(‘12’)
隐式转换 +-*/
‘12’-0
5.4.3. 转换为布尔型
方式
用法
Boolean()
Boolean(‘78’)
代表空,否定的值会被转换为false,如:0,NaN,undefined,null
其余值都会转换为true
6. 数组 6.1. 创建数组 1 2 3 4 5 6 var arr = new Array ();arr =[]; arr=['' ,'' ,'' ];
6.2. 数组操作方法
方法名
说明
返回值
push(参数1,参数2,…)
末尾添加一个或多个元素
返回新数组长度
pop()
删除数组最后一个元素
返回删除的元素值
unshift(参数1,参数2,…)
向数组的开头添加一个或更多元素
返回新数组长度
shift()
删除数组第一个元素
返回第一个元素的值
reverse()
翻转数组
sort()
数组排序
toString()
数组转换成字符串,逗号分隔每一项
join(‘分隔符’)
方法用于把数组中所有元素转换为一个字符串
7. 对象 7.1. 创建对象 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 var obj={};var obj = { uname :'hello' , age :18 , sex :'男' , say :function ( ){ console .log ('hi' ); } }; var obj = new Object ();obj.uname = 'hello' ; obj.say = function ( ){ console .log ('hi' ); } function Star (uname,age,sex ){ this .name = uname; this .age =age; this .sex =sex; }
8. DOM 文档对象模型 Document Object Model
w3c组织推荐的处理html的标准编程接口
可以用来改变网页内容,结构和样式
8.1. 获取元素 8.1.1. 根据ID获取 getElementById() 返回一个匹配特定 id 的元素. 由于元素的 ID 在大部分情况下要求是独一无二的,这个方法自然而然地成为了一个高效查找特定元素的方法
1 var element = document .getElementById (id);
参数
**element
**是一个 Element 对象。
**id
**是大小写敏感的字符串,代表了所要查找的元素的唯一ID.
返回值
返回一个匹配到 ID 的 DOM Element
对象
8.1.2. 根据标签名获取集合 getElementsByTagName() 返回一个包括所有给定标签名称的元素的HTML集合
1 var elements = document .getElementsByTagName (name);
8.1.3. 根据类名获取集合 getElementsByClassName() 1 var elements = document .getElementsByClassName ('类名' );
8.1.4. 根据选择器获取对象 querySelector() 参数可以是类(.class),id(#id),标签(li)
返回当前文档中第一个类名为 “myclass
“ 的元素
1 var el = document .querySelector (".myclass" );
8.1.5. 根据选择器获取集合 querySelectorAll() 1 var el = document .querySelectorAll ("li" );
8.2. 获取body元素 1 var bodyEle = document .body
8.3. 获取html元素 1 var element = document .documentElement ;
8.4. 操作元素 8.4.1. 改变元素内容 不识别html标签,非官方,去掉空格和换行
识别html标签,保留空格和换行
8.4.2. 修改元素属性 src,href,id,alt,title
1 2 var ele = document .querySelector ("img" );ele.src ="image/xx.jpg" ;
8.4.3. 修改元素样式 element.style 行内元素
element.className 类名样式
1 2 3 4 5 div.onclick =function ( ){ this .style .backgroundColor ="#fff" ; }
8.5. 操作元素属性
设置自定义属性
element.setAttribute(属性名,属性值);
获取属性值
element.getAttribute(属性名);
移除属性
element.removeAttribute(属性名);
H5自定义属性
dataset
中存放了element元素中所有以data开头自定义属性
element.getAttribute(“data-index”);
element.dataset.index
element.dataset[“index”]
8.6. 节点 8.6.1. 父节点 1 2 var ele = document .querySelector ("div" );var p = div.parentNode ;
parentNode 属性返回节点的最近的一个
父节点
指定的结点没有父节点则返回null
8.6.2. 子节点 文本节点 - 3
元素节点 - 1
8.6.3. 兄弟节点
nextElementSibling
下一个兄弟节点
previousElementSibling
上一个兄弟节点
8.6.4. 创建节点
不同浏览器下,innerHTML效率高于createElement
8.6.5. 删除节点 1 2 3 4 var ul = document .querySelector ("ul" );ul.removeChild (ul.children [0 ]);
8.6.6. 复制节点
如果括号参数为空或者false,浅拷贝,只复制标签,不复制内容
8.7. 事件 8.7.1. 注册事件/绑定事件 8.7.1.1. 传统注册方式 onxxx 用 on
开头的事件
事件 唯一
:同一个元素同一个事件只能设置一个处理函数,最后注册的处理函数将会覆盖前面注册的处理函数
鼠标事件
触发条件
onclick
鼠标点击左键触发
onmouseover
鼠标经过触发,会冒泡,影响父盒子
onmouserenter
鼠标经过触发,不会冒泡,不影响父盒子
onmouseout
鼠标离开触发,会冒泡,影响父盒子
onmouserleave
鼠标离开触发,不会冒泡,不影响父盒子
onfocus
获得鼠标焦点触发
onblur
失去鼠标焦点触发
onmousemove
鼠标移动触发
onmouseup
鼠标弹起触发
onmousedown
鼠标按下触发
用法
1 2 3 btn.onclick =function ( ){ }
8.7.1.2. 方法监听注册事件 addEventListener eventTarget.addEventListener(type,Listener,useCapture)
用法
1 2 3 btn.addEventListener ("click" ,function ( ){ })
事件
事件
触发条件
contextmenu
控制应该如何显示上下文菜单
selectstart
开始时选中
DOMContentLoaded
事件触发时,仅当DOM加载完成,不包括样式表,图片,flash等。ie9+支持
resize
调整窗口大小
pageshow
页面显示时触发,无论页面是否来自缓存
8.7.2. 删除事件/解绑事件 8.7.2.1. 传统方式
8.7.2.2. 方法监听方式 1 btn.removeEventListener (type,Listener ,useCapture);
这里的事件处理函数不能使用匿名函数
8.7.3. 事件流 页面中接收事件的顺序
⚠️注意:
js代码只能执行捕获或冒泡其中的一个阶段
onclick和attachEvent只能得到冒泡阶段
addEventListener(type,Listener,useCapture)第三个参数如果是true,表示在捕获阶段调用事件处理程序;如果是false,或者不填,表示在事件冒泡阶段调用事件处理程序
实际开发中少用事件捕获,更关注事件冒泡
有些事件没有冒泡,onblur,onmouseenter,onmouseleave
div注册点击事件:
捕获阶段:document -> html -> body -> div
冒泡阶段:div -> body-> html-> document
8.7.4. 事件对象 1 2 3 btn.onclick =function (e ){ e=e||window .event ; }
window.event
ie678使用
e对象代表事件的状态,比如键盘按键的状态,鼠标的位置,鼠标按钮的状态
e变量中存放了跟事件相关的一系列信息数据的集合
事件对象属性方法
说明
e.target
返回的是触发事件的对象,标准
this
返回的是绑定事件的对象
e.srcElement
返回的是触发事件的对象,ie678,非标准
e.type
返回对象的类型,click,mouseover,…,不带on
e.cancelBubble
阻止冒泡,ie678
e.returnValue
阻止默认事件,ie678,非标准
e.preventDefault()
阻止默认事件,标准
e.stopPropagation()
阻止冒泡,标准
e.target vs this
如li包裹在整个ul中,点击某个li,this指向ul,e.target指向li
1 2 3 4 ul.onclick =function (e ){ var li = e.target ; var ul = this ; }
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 var btn = document .querySelector ("button" );btn.addEventListener ("click" ,function (e ){ e.preventDefault (); }) btn.onclick =function (e ){ e.preventDefault (); e.returnValue ; return false ; alert (123 ); }
8.7.5. 禁止文字选中 禁止鼠标右键菜单,contextmenu
控制应该如何显示上下文菜单,用于取消默认的上下文菜单
1 2 3 document .addEventListener ("contextmenu" ,function (e ){ e.preventDefault (); })
禁止鼠标选中,selectstart
开始时选中
1 2 3 document .addEventListener ("selectstart" ,function (e ){ e.preventDefault (); })
8.7.6. 鼠标事件 MouseEvent event 对象代表事件的状态,跟事件相关的一系列信息的集合。
鼠标事件对象
说明
e.clientX
返回鼠标相对于浏览器窗口可视区的X坐标
e.clientY
返回鼠标相对于浏览器窗口可视区的Y坐标
e.pageX
返回鼠标相对于文档页面的X坐标,IE+9支持
e.pageY
返回鼠标相对于文档页面的Y坐标,IE+9支持
e.screenX
返回鼠标相对于电脑屏幕的X坐标
e.screenY
返回鼠标相对于电脑屏幕的Y坐标
8.7.7. 键盘事件 keyEvent
键盘事件
触发事件
onkeyup
某个键盘按键被松开时触发
onkeydown
某个键盘按键被按下时触发
onkeypress
某个键盘按键被按下时触发,不识别功能键,ctrl,shift,箭头等
执行顺序:onkeydown,onkeypress,onkeyup
按键识别 e.keyCode
返回的是键对应的ASCII码
keydown,keyup不区分大小写
keypress区分大小写
A-65,a-97
8.8. 案例一:隐藏文本内容 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > input { color : #999 ; } </style > </head > <body > <input type ="text" value ="请输入" > <script > var ele = document .querySelector ("input" ); ele.onfocus =function ( ){ if (ele.value =='请输入' ){ ele.value ='' ; } ele.style .color ="#000" ; } ele.onblur =function ( ){ if (ele.value =='' ){ ele.value ='请输入' ; ele.style .color ="#999" ; }else { ele.style .color ="#000" ; } } </script > </body > </html >
8.9. 案例二:密码框验证信息 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > .error { color : red; } .success { color : green; } </style > </head > <body > <input type ="text" value ="" > <span > </span > <script > var ele = document .querySelector ('input' ); var verify = document .querySelector ('span' ); ele.onblur =function ( ){ if (this .value .length <6 ||this .value .length >10 ){ verify.innerHTML ="请输入6到10位密码" ; verify.className ="error" ; }else { verify.innerHTML ="格式正确" ; verify.className ="success" ; } } </script > </body > </html >
8.10. 案例三:tab栏切换 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > *{ margin : 0 ; padding : 0 ; } .current { background-color : red; color : #fff ; } .tab_list { width : 600px ; height : 50px ; border-bottom : 1px solid #000 ; margin : 0 auto; } .tab_list ul { list-style : none; width : 100% ; height : 100% ; } .tab_list ul li { float : left; width : 100px ; height : 100% ; text-align : center; line-height : 50px ; } .tab_con { width : 600px ; height : 100px ; margin : 0 auto; } .content { display : none; } </style > </head > <body > <div class ="tab" > <div class ="tab_list" > <ul > <li class ="current" > 商品介绍</li > <li > 规格与包装</li > <li > 售后保障</li > <li > 商品评价</li > <li > 手机社区</li > </ul > </div > <div class ="tab_con" > <div class ="item" > 商品介绍模块内容 </div > <div class ="item content" > 规格与包装模块内容 </div > <div class ="item content" > 售后保障模块内容 </div > <div class ="item content" > 商品评价模块内容 </div > <div class ="item content" > 手机社区模块内容 </div > </div > </div > <script > var ele = document .querySelector (".tab_list" ).querySelectorAll ('li' ); var content = document .querySelector (".tab_con" ).querySelectorAll (".item" ); for (var i=0 ;i<ele.length ;i++){ ele[i].setAttribute ("index" ,i); ele[i].onclick =function ( ){ for (var i=0 ;i<ele.length ;i++){ ele[i].removeAttribute ("class" ); } this .className ="current" ; for (var i=0 ;i<content.length ;i++){ content[i].style .display ="none" ; } var index = this .getAttribute ("index" ); content[index].style .display ="block" ; } } </script > </body > </html >
8.11. 案例四:百度换肤 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > body { background-repeat : no-repeat; background-position : 0 0 ; background-size : 100% ; } ul { list-style : none; width : 1000px ; margin : 0 auto; } ul li { float : left; width : 200px ; height : 100px ; margin : 10px ; border : 1px solid #000 ; } ul li img { width : 100% ; height : 100% ; } </style > </head > <body > <ul > <li > <img src ="images/1.jpg" alt ="" > </li > <li > <img src ="images/2.jpg" alt ="" > </li > <li > <img src ="images/3.jpg" alt ="" > </li > <li > <img src ="images/4.jpg" alt ="" > </li > </ul > <script > var li = document .querySelectorAll ("li" ); for (var i=0 ;i<li.length ;i++){ li[i].onmouseover =function ( ){ var src = this .querySelector ("img" ).src ; console .log (src); document .body .style .backgroundImage ='url(' +src+')' ; } } </script > </body > </html >
8.12. 案例五:留言板 添加节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > ul { list-style : none; margin : 0 ; padding : 0 ; width : 250px ; } ul li { display : block; height : 30px ; background-color : pink; margin : 5px ; } </style > </head > <body > <textarea name ="" id ="text" cols ="30" rows ="10" placeholder ="请输入内容" > </textarea > <button > 发布</button > <ul > </ul > <script > var btn = document .querySelector ("button" ); var text = document .querySelector ("#text" ); var ul = document .querySelector ("ul" ); btn.onclick =function ( ){ if (text.value .length ==0 ){ alert ("请输入内容" ); }else { var li = document .createElement ("li" ); li.innerHTML =text.value ; ul.insertBefore (li,ul.children [0 ]); } for (var i=0 ;i<ul.children .length ;i++){ ul.children [i].firstElementChild .onclick =function ( ){ ul.removeChild (this .parentNode ); } } } </script > </body > </html >
8.13. 案例六:表格操作 创建节点,删除节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > table { margin : 0 auto; } table tr { display : table-row; border-color : inherit; vertical-align : inherit; } </style > </head > <body > <table > <thead > <tr > <th > 姓名</th > <th > 年龄</th > <th > 性别</th > <th > 操作</th > </tr > </thead > <tbody > </tbody > </table > <script > var data=[ {uname : 'AAA' ,age : 18 ,sex : 'M' }, {uname : 'BBB' ,age : 19 ,sex : 'F' }, {uname : 'CCC' ,age : 18 ,sex : 'F' }, {uname : 'DDD' ,age : 20 ,sex : 'M' } ]; var tbody = document .querySelector ("tbody" ); for (var i=0 ;i<data.length ;i++){ var tr = document .createElement ("tr" ); for (var k in data[i]){ var td = document .createElement ("td" ); td.innerHTML =data[i][k]; tr.appendChild (td); } var td = document .createElement ("td" ); td.innerHTML ="<a href='javascript:;'>删除</a>" ; tr.appendChild (td); tbody.appendChild (tr); } var a = tbody.querySelectorAll ("a" ); for (var i=0 ;i<a.length ;i++){ a[i].onclick =function ( ){ tbody.removeChild (this .parentNode .parentNode ); } } </script > </body > </html >
8.14. 案例七:跟随鼠标移动 鼠标移动触发事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > img { position : absolute; top : 0 ; left : 0 ; display : none; transition : .5s ; } </style > </head > <body > <img src ="images/run.gif" alt ="" > <script > var img = document .querySelector ("img" ); document .addEventListener ("mousemove" ,function (event ) { var x = event.pageX ; var y = event.pageY ; img.style .display ="inline" ; img.style .top =y-img.height /2 +"px" ; img.style .left =x-img.width /2 +"px" ; }) </script > </body > </html >
8.15. 案例八:模拟京东按键输入内容 按键输入 keyup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > .box { position : relative; height : 100px ; width : 100px ; } .info { position : absolute; top : 0 ; left : 0 ; width : 200px ; height : 30px ; border : 1px solid #000 ; display : none; } input { margin-top : 35px ; width : 200px ; } </style > </head > <body > <div class ="box" > <div class ="info" > </div > <input type ="text" value ="" > </div > <script > var box = document .querySelector (".box" ); var input = box.querySelector ("input" ); var info = box.querySelector (".info" ); document .addEventListener ("keyup" ,function (event ){ if (event.keyCode ==83 ){ input.focus (); } if (input.value .length !=0 ){ info.style .display ="block" ; info.innerHTML =input.value ; }else { info.style .display ="none" ; } }) input.addEventListener ("blur" ,function ( ){ info.style .display ="none" ; }) input.addEventListener ("focus" ,function ( ){ if (this .value !='' ) { info.style .display ="block" ; } }) </script > </body > </html >
8.16. 案例九:元素拖动至指定位置 1 2 3 4 5 6 7 <div id ="container" > <h1 > Hello World</h1 > <p > 您好</p > </div > <div id ="box" > </div >
css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 body { position :relative; } container{ position :absolute; left :0 ; width :300px ; height :300px ; background :url ("1.png" ) no-repeat center center; } box{ position :absolute; right :0 ; width :300px ; height :300px ; background : #d4efdf ; }
js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 var con = document .getElementById ("container" );con.draggable =true ; var box =document .getElementById ("box" );box.ondragover = function (e ){ e.preventDefault (); } box.ondrop =function (e ){ box.appendChild (con); }
9. BOM Brower Object Model 浏览器对象模型,与浏览器窗口进行交互,核心对象是window
9.1. 窗口加载事件 load 窗口加载事件 onload
,当文档内容完全加载完成会触发该事件(包括图像,脚本文件,css文件等),就调用的处理函数。
1 2 3 4 5 6 window .onload =function ( ){ } window .addEventListener ("load" ,function ( ){ })
DOMContentLoaded
事件触发时,仅当DOM加载完成,不包括样式表,图片,flash等。ie9+支持
1 2 3 window .addEventListener ("DOMContentLoaded" ,function ( ){ })
9.2. 调整窗口大小事件 resize 1 2 3 4 window .addEventListener ("resize" ,function ( ){ var width = window .innerWidth (); var height = window .innerHeight (); })
9.3. 定时器 9.3.1. setTimeout() 定时器到期后执行调用函数
用法:window.setTimeout(调用函数,延时的毫秒数)
1 2 3 var timer = setTimeout (function ( ){ alert ("触发了" ); },2000 );
停止定时器
9.3.2. setInterval() 用法:window.setInterval(调用函数,间隔的毫秒数)
每隔这个时间,调用一次函数
window可以省略
函数可以直接写函数,或者函数名,或者取字符串函数名
间隔的毫秒数省略默认是0,如果写,必须是毫秒,表示每隔多少毫秒数就自动调用函数
可以给定时器赋值一个标识符
停止定时器 clearInterval()
9.3.3. 倒计时实现 setInterval()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > </head > <body > <p > </p > <script > var p= document .querySelector ("p" ); var checkTime = +new Date ("2020-05-11 00:00:00" ); getTime (); function getTime ( ){ var now = +new Date (); var num = (checkTime-now)/1000 ; var d = parseInt (num/60 /60 /24 ); var day = d>9 ?d+'' :'0' +d; var h = parseInt (num/60 /60 %24 ); var hour = h>9 ?h+'' :'0' +h; var m = parseInt (num/60 %60 ); var minute = m>9 ?m+'' :'0' +m; var s = parseInt (num%60 ); var second = s>9 ?s+'' :'0' +s; p.innerHTML = day+' 天 ' +hour+' 时 ' + minute+ ' 分 ' +second+ ' 秒' ; } setInterval (getTime,1000 ); </script > </body > </html >
9.3.4. 发送短信 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > </head > <body > <button > 发送</button > <script > var btn = document .querySelector ("button" ); btn.addEventListener ("click" ,function ( ){ this .disabled =true ; var index = 5 ; btn.innerHTML = '还剩下' +(index--)+'秒' ; var timer = setInterval (function ( ){ if (index!=0 ){ btn.innerHTML = '还剩下' +(index--)+'秒' ; } else { btn.disabled =false ; clearInterval (timer); btn.innerHTML ='发送' ; } },1000 ); }); </script > </body > </html >
9.4. this指向
全局作用域或者普通函数中this指向全局对象window
定时器中的this指向window
方法调用中谁调用this指向谁
构造函数中this指向构造函数的实例
9.5. location 9.5.1. 对象
属性
返回值
location.href
获取或者设置整个url
location.host
返回主机
location.port
返回端口号
location.pathname
返回路径
location.search
返回参数
location.hash
返回片段 #后面内容 常见于链接 锚点
9.5.2. 方法
对象方法
返回值
location.assign(url)
跟href一样,可以跳转页面
location.replace()
替换当前页面,因为不记录历史,所以不能后退页面
location.reload()
重新加载页面,相当于刷新按钮或者f5,如果参数为true,强制刷新ctrl+f5
9.5.3. 案例:5秒后跳转页面 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > </head > <body > <p > </p > <script > var p = document .querySelector ("p" ); var index = 5 ; p.innerHTML = (index--)+'秒后跳转' ; var timer = setInterval (function ( ){ if (index!=0 ){ p.innerHTML = (index--)+'秒后跳转' ; } else { clearInterval (timer); location.href ="http://www.baidu.com" ; } },1000 ); </script > </body > </html >
9.6. navigator 有关浏览器的信息,可以判断用户打开页面的终端是手机还是pc
1 2 3 4 5 6 7 if ((navigator.userAgent .match (/(phone|pad|iphone|ipod|Abdroid)/i ))){ window .location .href ="" ; }else { window .location .href ="" ; }
9.7. history 历史记录交互,包含用户访问过的url
方法
作用
back()
后退
forward()
前进
go(参数)
正数前进,负数后退
9.8. 元素偏移量 offset offset翻译过来就是偏移量,使用offset系列相关属性可以动态的得到该元素的位置,大小等。
获得元素距离带有定位
父元素的位置
获得元素自身的大小
返回的数值不带单位
属性
offset系列属性
作用
element.offsetParent
返回作为该元素带有定位的父级元素,父级没定位则返回body
element.offsetTop
返回元素相对带有定位父元素上方的偏移
element.offsetLeft
返回元素相对带有定位父元素左边框的偏移
element.offsetWidth
返回元素自身包括padding,边框,内容区的宽度,返回数值不带单位
element.offsetHeight
返回自身包括padding,边框,内容区的高度,返回数值不带单位
9.8.1. offset vs style
Offset
style
offset可以得到任意样式表的样式值
style只能得到行内样式
表中的样式值
offset系列获取的数值是没有单位的
style.width获得的还是带有单位的字符串
offsetWidth包含
padding+border+width
style.width获得不包含
padding和border的值
offsetWidth等属性是只读
属性,只能获取不能赋值
style.width是可读写属性,可以获取也可以赋值
获取元素大小位置,用offset合适
给元素更改值,用style
9.8.2. 获取鼠标在盒子内的坐标 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > div { width : 200px ; height : 200px ; background-color : pink; } </style > </head > <body > <div > </div > <script > var div = document .querySelector ("div" ); div.addEventListener ("click" ,function (e ){ var pagex = e.pageX ; var pagey = e.pageY ; console .log ("page: " +pagex,pagey); var divx = div.offsetLeft ; var divy = div.offsetTop ; var x = pagex - divx; var y = pagey - divy; console .log (x,y); }); </script > </body > </html >
9.8.3. 模态框拖拽
点击弹出层,弹出模态框,并且显示灰色半透明的遮挡层
点击关闭按钮,关闭模态框,同时关闭灰色半透明的遮挡层
鼠标放到模态框最上面一行,可以按住鼠标拖拽模态框在页面中移动
鼠标松开,可以停止模态框移动
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 h1.addEventListener ("mousedown" ,function (e ){ var x = e.pageX - box.offsetLeft ; var y = e.pageY - box.offsetTop ; document .addEventListener ("mousemove" ,move); function move (e ){ box.style .left = e.pageX - x + 'px' ; box.style .top = e.pageY - y + 'px' ; } document .addEventListener ("mouseup" ,function ( ){ document .removeEventListener ("mousemove" ,move); }); });
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > html ,body { width : 100% ; height : 100% ; } a { text-decoration : none; color : #333 ; } .box { position : absolute; top : 50% ; left : 50% ; transform : translate (-50% ,-50% ); width : 70% ; height : 70% ; background-color : #fff ; z-index : 2 ; display : none; text-align : center; } .box h1 { cursor : move; } .box .cancel { position : absolute; top : 0 ; right : 0 ; width : 50px ; height : 50px ; transform : translate (50% ,-50% ); border-radius : 50% ; background-color : #fff ; text-align : center; } .box .cancel a { text-decoration : none; color : #333 ; font-size : 20px ; margin-top : 15px ; display : block; } .mask { position : absolute; top : 0 ; left : 0 ; width : 100% ; height : 100% ; display : none; background-color : rgba (0 ,0 ,0 ,.6 ); transition : .5s ; } </style > </head > <body > <a href ="javascript:;" > 点击弹出框</a > <div class ="mask" > </div > <div class ="box" > <h1 > content</h1 > <div class ="cancel" > <a href ="javascript:;" > X</a > </div > </div > <script > var a = document .querySelector ("a" ); var mask = document .querySelector (".mask" ); var box = document .querySelector (".box" ); var h1 = box.querySelector ("h1" ); var cancel = box.querySelector (".cancel" ); a.addEventListener ("click" ,function ( ){ mask.style .display ='block' ; box.style .display ='block' ; }); cancel.addEventListener ("click" ,function ( ){ mask.style .display ='none' ; box.style .display ='none' ; }); h1.addEventListener ("mousedown" ,function (e ){ var x = e.pageX - box.offsetLeft ; var y = e.pageY - box.offsetTop ; document .addEventListener ("mousemove" ,move); function move (e ){ box.style .left = e.pageX - x + 'px' ; box.style .top = e.pageY - y + 'px' ; } document .addEventListener ("mouseup" ,function ( ){ document .removeEventListener ("mousemove" ,move); }); }); </script > </body > </html >
9.8.4. 仿京东放大镜效果
$\frac{遮挡层移动距离}{遮挡层最大移动距离}$ = $\frac{大图片移动距离}{大图片最大移动距离}$
大图片移动距离 = 遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > .box { position : relative; width : 200px ; height : 200px ; border : 1px solid #999 ; margin-left : 400px ; cursor : move; } .box .small { width : 100% ; } .box .mask { position : absolute; top : 0 ; left : 0 ; background-color : rgba (241 , 202 , 5 , 0.5 ); width : 120px ; height : 120px ; border : 1px solid yellow; display : none; } .box .bigimg { position : absolute; top : 0 ; left : 210px ; width : 400px ; height : 400px ; border : 1px solid #999 ; overflow : hidden; display : none; } .box .bigimg .big { position : absolute; top : 0 ; left : 0 ; } </style > </head > <body > <div class ="box" > <img src ="images/iPhone.jpg" alt ="" class ="small" > <div class ="mask" > </div > <div class ="bigimg" > <img src ="images/iPhoneX2.jpg" alt ="" class ="big" > </div > </div > <script > var box = document .querySelector (".box" ); var mask = box.querySelector (".mask" ); var bigdiv = box.querySelector (".bigimg" ); var big = bigdiv.querySelector (".big" ); box.addEventListener ("mouseover" ,function ( ){ mask.style .display = "block" ; bigdiv.style .display = "block" ; }); box.addEventListener ("mousemove" ,function (e ){ var x = e.pageX - box.offsetLeft - mask.offsetWidth /2 ; var y = e.pageY - box.offsetTop - mask.offsetHeight /2 ; var limitx = box.clientWidth -mask.offsetWidth ; var limity = box.clientHeight -mask.offsetHeight ; if (x<0 ){ x=0 ; } if (x>limitx){ x=limitx; } if (y<0 ){ y=0 ; } if (y>limity){ y=limity; } mask.style .left = x + 'px' ; mask.style .top = y + 'px' ; var biglimitx = big.offsetWidth - bigdiv.offsetWidth ; var biglimity = big.offsetHeight - bigdiv.offsetHeight ; var bigx = x*biglimitx/limitx; var bigy = y*biglimity/limity; big.style .left = -bigx + 'px' ; big.style .top = -bigy + 'px' ; }); box.addEventListener ("mouseout" ,function ( ){ mask.style .display = "none" ; bigdiv.style .display = "none" ; }); </script > </body > </html >
9.9. 元素可视区 client 动态得到元素的边框大小,元素大小
属性
作用
element.clientTop
返回元素上边框大小
element.clientLeft
返回元素左边框大小
element.clientWidth
返回自身包括padding,内容区的宽度,不含边框,返回数值不带单位
element.clientHeight
返回自身包括padding,内容区的高度,不含边框,返回数值不带单位
动态获取元素的大小,滚动距离
属性
作用
element.scrollTop
返回被卷去的上侧距离,返回数值不带单位
element.scrollLeft
返回被卷去的左侧距离,返回数值不带单位
element.scrollWidth
返回自身实际的宽度,不含边框,含padding,返回数值不带单位
element.scrollHeight
返回自身实际的高度,不含边框,含padding,返回数值不带单位
window.pageYOffset
页面被卷去的头部
9.10.1. 仿淘宝固定右侧侧边栏 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > body { width : 1120px ; margin : 0 auto; } .w { margin-bottom : 10px ; font-size : 50px ; line-height : 50px ; color : #fff ; text-align : center; } .header { height : 200px ; background-color : pink; } .banner { height : 300px ; background-color : red; } .main { height : 800px ; background-color : purple; } .slide-bar { position : absolute; top : 255px ; right : 50px ; width : 80px ; height : 200px ; background-color : rgb (247 , 100 , 142 ); } .slide-bar .goBack { opacity : 0 ; transition : .5s ; } </style > </head > <body > <div class ="slide-bar" > <span class ="goBack" > 返回顶部</span > </div > <div class ="header w" > 头部-200</div > <div class ="banner w" > banner-300</div > <div class ="main w" > 主体-800</div > <script > var header = document .querySelector (".header" ); var banner = document .querySelector (".banner" ); var main = document .querySelector (".main" ); var slide = document .querySelector (".slide-bar" ); var span = slide.querySelector (".goBack" ); var slideTop = slide.offsetTop - banner.offsetTop ; document .addEventListener ("scroll" ,function (e ){ var scrollY = getScroll ().top ; if (scrollY>=banner.offsetTop ){ slide.style .position = 'fixed' ; slide.style .top = slideTop +'px' ; }else { slide.style .position = 'absolute' ; slide.style .top = "255px" ; } if (scrollY>=main.offsetTop ){ span.style .opacity = 1 ; }else { span.style .opacity = 0 ; } }); function getScroll ( ){ return { left : window .pageXOffset || document .documentElement .scrollLeft || document .body .scrollLeft || 0 , top : window .pageYOffset || document .documentElement .scrollTop || document .body .scrollTop || 0 } } </script > </body > </html >
9.10.2. 缓动动画-返回顶部 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 span.addEventListener ("click" ,function ( ){ animate (window ,0 ); }); function animate (obj,target,callback ){ clearInterval (obj.timer ); obj.timer = setInterval (function ( ){ step = (target-window .pageYOffset )/10 ; step=step>0 ?Math .ceil (step):Math .floor (step); window .scroll (0 ,window .pageYOffset + step); if (window .pageYOffset ==target){ clearInterval (obj.timer ); callback&&callback (); } },15 ); }
offset经常用于获得元素位置 offsetLeft,offsetTop
client经常用于获取元素大小 clientWidth,clientHeight
scroll经常用于获取滚动距离 scrollTop,scrollLeft
页面滚动距离 window.pageXoffset
9.12. 立即执行函数 1 2 3 (function ( ){})(); (function ( ){}());
9.13. pageshow事件 1 2 3 4 5 6 7 document .addEventListener ("pageshow" ,function (e ){ if (e.persisted ){ } });
9.14. 缓动动画 缓动移动距离 = (目标值-现在的位置)/10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <style > html ,body { width : 100% ; } div { position : absolute; top : 100px ; left : 0 ; width : 50px ; height : 50px ; background-color : pink; } </style > </head > <body > <button class ="go" > 前进</button > <button class ="back" > 后退</button > <div > </div > <script > var div = document .querySelector ("div" ); var go = document .querySelector (".go" ); var back = document .querySelector (".back" ); function animate (obj,target,callback ){ clearInterval (obj.timer ); obj.timer = setInterval (function ( ){ step = (target-obj.offsetLeft )/10 ; step=step>0 ?Math .ceil (step):Math .floor (step); obj.style .left = obj.offsetLeft + step + 'px' ; if (obj.offsetLeft ==target){ clearInterval (obj.timer ); if (callback){ callback (); } } },15 ); } go.addEventListener ("click" ,function ( ){ animate (div,500 ); }); back.addEventListener ("click" ,function ( ){ animate (div,0 ,function ( ){ div.style .backgroundColor ="red" ; }); }); </script > </body > </html >
9.14.1. 封装缓动动画-侧边栏
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > Document</title > <script src ="fun.js" > </script > <style > .direction { position : absolute; left : 0 ; top : 500px ; width : 30px ; height : 30px ; background-color : pink; z-index : 1 ; color : #fff ; } .word { position : absolute; left : -200px ; top : 500px ; width : 200px ; height : 30px ; background-color : pink; text-align : right; color : #fff ; } </style > </head > <body > <div class ="direction" > -></div > <di class ="word" > 展开</di > <script > var direction = document .querySelector (".direction" ); var word = document .querySelector (".word" ); direction.addEventListener ("mouseenter" ,function ( ){ animate (word,0 ,function ( ){ direction.innerHTML ='<-' ; }); }); direction.addEventListener ("mouseleave" ,function ( ){ animate (word,-200 ,function ( ){ direction.innerHTML ='->' ; }); }); </script > </body > </html >
9.15. 图片轮播 9.15.1. 无缝轮播
声明一个变量,点击一次,自增1,这个变量乘以图片宽度,就是ul的距离
图片无缝滚动原理
把ul第一个li复制一份,放到ul最后
当图片滚动到克隆的最后一张图片时,让ul快速的,不做动画的跳到最左侧,left=0
同时num赋值为0,可以重新开始滚动图片
9.15.2. 节流阀 防止轮播图按钮连续点击造成播放过快
利用回调函数,添加变量来控制,锁住函数和解锁函数
9.15.3. 代码 html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 <!DOCTYPE html > <html lang ="zh-CN" > <head > <meta charset ="UTF-8" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > 小兔鲜儿-新鲜,惠民,快捷!</title > <meta name ="description" content ="小兔鲜儿官网,致力于打造全球最大的食品,生鲜电商购物平台。" > <meta name ="keywords" content ="小兔鲜儿,食品,生鲜,服装,家电,电商,购物" > <link rel ="shortcut icon" href ="favicon.ico" type ="image/x-icon" > <link rel ="stylesheet" href ="css/base.css" > <link rel ="stylesheet" href ="css/common.css" > <link rel ="stylesheet" href ="css/index.css" > <script src ="js/animate.js" > </script > <script src ="js/index.js" > </script > </head > <body > <div class ="xtx-entry" > <div class ="container" > <ul class ="banner" > <li > <a href ="" > <img src ="images/1.jpg" alt ="" > </a > </li > <li > <a href ="" > <img src ="images/2.jpg" alt ="" > </a > </li > <li > <a href ="" > <img src ="images/3.jpg" alt ="" > </a > </li > <li > <a href ="" > <img src ="images/4.jpg" alt ="" > </a > </li > </ul > <a href ="javascript:;" class ="prev leftrightbutton" > <</a > <a href ="javascript:;" class ="next leftrightbutton" > ></a > <ol class ="indicator" > </ol > </div > </div > </body > </html >
css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 .xtx-entry .container { height : 500px ; background-color : pink; position : relative; overflow : hidden; width : 1240px ; } .xtx-entry .banner { position : absolute; top : 0 ; left : 0 ; width : 6200px ; } .xtx-entry .banner li { float : left; } .xtx-entry .banner li a img { width : 1240px ; height : 500px ; } .xtx-entry .prev { left : 260px ; display : none; } .leftrightbutton { width : 45px ; height : 45px ; background-color : rgba (0 ,0 ,0 ,.2 ); border-radius : 50% ; position : absolute; top : 228px ; line-height : 45px ; color : #fff ; font-size : 20px ; box-sizing : border-box; padding-left : 15px ; } .xtx-entry .next { right : 10px ; display : none; } .xtx-entry .indicator { width : 110px ; height : 10px ; position : absolute; top : 459px ; left : 680px ; } .xtx-entry .indicator li { width : 10px ; height : 10px ; background-color : rgba (255 ,255 ,255 ,.3 ); border-radius : 50% ; float : left; margin-right : 15px ; } .xtx-entry .indicator li :last-child { margin-right : 0 ; } .active { background-color : #fff !important ; }
js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 window .addEventListener ("load" ,function ( ){ var entry = document .querySelector (".xtx-entry" ); var leftbtn = entry.querySelector (".prev" ); var rightbtn = entry.querySelector (".next" ); var container = entry.querySelector (".container" ); container.addEventListener ("mouseenter" ,function ( ){ leftbtn.style .display ="block" ; rightbtn.style .display ="block" ; clearInterval (imgtimer); imgtimer=null ; }); container.addEventListener ("mouseleave" ,function ( ){ leftbtn.style .display ="none" ; rightbtn.style .display ="none" ; imgtimer=setInterval (function ( ){ rightbtn.click (); },2000 ); }); var width = container.offsetWidth ; var banner = entry.querySelector (".banner" ); var indicator = entry.querySelector (".indicator" ); for (var i=0 ;i<banner.children .length ;i++){ var li = document .createElement ("li" ); indicator.appendChild (li); if (i==0 ){ li.className ="active" ; } li.setAttribute ("index" ,i); li.addEventListener ("click" ,function ( ){ for (var i=0 ;i<indicator.children .length ;i++){ indicator.children [i].className ='' ; } this .className ='active' ; var index = this .getAttribute ("index" ); num=index; animate (banner,-index*width); }); } var firstimg = banner.children [0 ].cloneNode (true ); banner.appendChild (firstimg); var num = 0 ; var flag = true ; rightbtn.addEventListener ("click" ,function ( ){ if (flag){ flag = false ; if (num==banner.children .length -1 ){ num=0 ; banner.style .left =0 ; } num++; for (var i=0 ;i<indicator.children .length ;i++){ indicator.children [i].className ='' ; } if (num==banner.children .length -1 ){ indicator.children [0 ].className ='active' ; }else { indicator.children [num].className ='active' ; } animate (banner,-num*width,function ( ){ flag = true ; }); } }); leftbtn.addEventListener ("click" ,function ( ){ if (flag){ flag=false ; if (num==0 ){ num=banner.children .length -1 ; banner.style .left =(-num*width)+'px' ; } num--; for (var i=0 ;i<indicator.children .length ;i++){ indicator.children [i].className ='' ; } indicator.children [num].className ='active' ; animate (banner,-num*width,function ( ){ flag=true ; }); } }); var imgtimer = setInterval (function ( ){ rightbtn.click (); },2000 ); });
10. 本地存储
数据存储在用户浏览器中
设置,读取方便,甚至页面刷新不丢失数据
容量较大,sessionStorage约5M,localStorage约30M
只能存储字符串,可以将对象JSON.stringify()编码后存储
10.1. sessionStorage 生命周期为关闭浏览器窗口
同一个窗口下数据共享
以键值对形式存储
1 2 3 4 5 6 7 8 9 10 11 sessionStorage.setItem (key,value); sessionStorage.getItem (key); sessionStorage.removeItem (key); sessionStorage.clear ();
10.2. localStorage 生命周期为永久有效,除非手动删除
同一个浏览器下数据共享
以键值对形式存储
1 2 3 4 5 6 7 8 9 10 11 localStorage .setItem (key,value);localStorage .getItem (key);localStorage .removeItem (key);localStorage .clear ();