DOM实战
作者声明:本博客中所写的文章,都是博主自学过程的笔记,参考了很多的学习资料,学习资料和笔记会注明出处,所有的内容都以交流学习为主。有不正确的地方,欢迎批评指正
视频来源:https://www.bilibili.com/video/av26087098
DOM
课程内容介绍
1.1 DOM与BOM的概念
文档结构树
BOM与DOM完整结构图
document对象
示例代码 document
<script> // document.URL 可以获取当前文档的地址 console.log( window.document.URL ); // document.title 获取或者是设置 head标签中的title标签的文本内容 console.log( window.document.title ); document.title = "我学习的视频是老马前端系列视频"; console.log( document.title ); // 输出编码 console.log( document.charset ); </script>
示例代码 浏览器时钟
<script> // window.setIntervar() // 可以传两个参数 // 1 要执行的代码段(可以是一个函数,也可以是一段代码字符串) // 2 要间隔执行代码段的毫秒数 var t = setInterval(function(){ // console.log(1); console.log(new Date()); },1000); //不推荐使用 代码字符串的方式 // setInterval("console.log(new Date());",2000); //setTimeout(fun,delay); //延迟delay毫秒之后,执行代码段(函数)但只执行一次 setTimeout(function(){ console.log( "laoma" ); console.log( t ); clearInterval( t ); //停止间断循环执行的setInterval },5000); </script>
案例
示例代码 跑马灯
<script> // console.log( document.title ); // 没隔0.5s 让title的最后一个文字放到title的最前面去 // 1s = 1000ms setInterval(function(){ // 让title最后一个文字放到title最前面去 // 使用字符数组的方法 // 数组 pop 方法可以从数组的最后一个位置弹出一个元素 //unshift方法可以从数组的头部添加元素 // 字符串转字符数组 var charArray = document.title.split(""); // 让字符数组的最后一个元素出数组 var lastChar = charArray.pop(); // 把最后一个元素查到数组的开头 charArray.unshift( lastChar ); // 把字符数组转成字符串 var newTitle = charArray.join( "" ); // 把新的标题改到浏览器上去 document.title = newTitle; },500); </script>
示例代码 跑马灯slice方法
<script> // 实现跑马灯 var intervalID = setInterval(function(){ // 拿到当前的页面的title var oldTitle = document.title; // 拿到当前页面title的最后一个字符 // slice方法,可以接受两个参数 // 第一个参数 截取字符串起始位置 第二个参数 技术位置 // slice方法不影响原来的字符串,截取到最后一个字符串的前一个位置 var lastChar = oldTitle.slice( oldTitle.length - 1 ); var beforeStr = oldTitle.slice( 0,oldTitle.length - 1 ); document.title = lastChar + beforeStr; },500); // 5秒钟之后,执行清除时钟的代码 setTimeout(function(){ clearInterval( intervalID ); },5000); </script>
访问DOM树上的节点
getElementById
示例代码
<body> <!-- p#p${段落$}*3 --> <p id="p1">段落1</p> <p id="p2">段落2</p> <p id="p3">段落3</p> <div class= "" id = "d1"></div> <script> // 根据标签的id的值在文档中搜索标签 var elementP = document.getElementById( "p2" ); console.log( elementP ); //elementP → HTMLParagraphElement(段落标签原型) → HTMLElement(所有HTML标签的基类 接口) → Element → Node → EventTarget → Object → null //接口 有自己规定的方法 属性 但必须有子类给他实现 Element Node //类型 可直接创建实例 比如 Number类型 var d1 = document.getElementById( "d1" ); //d1 => HTMLDivElement var d2 = document.getElementById( "ufsoi" ); //d2 => null 一般情况下如果函数没有具体的值,一般都会返回null </script> </body>
Element 元素对象接口详解
示例代码
<body> <div id = "d1" class = "ts" laoma = "sss" > <span>你好</span> <p>大家好</p> </div> <script> // 获取到id = d1 的div标签 var d1 = document.getElementById( "d1" ); // d1 HTMLDivElement HTMLElement Element // d1.attributes(); //属性 console.log( d1.attributes ); // d1.attributesa(0) console.log( d1.attributes.item(0) ); // 设置属性的值 d1.setAttribute( "laoma","123" ); console.log(d1.getAttribute("class")); console.log( d1.className ); console.log( d1.id ); // 删除属性 d1.removeAttribute( "laoma" ); </script> </body>
示例代码
<body> <p>1-1</p> <p>2-2</p> <p>3-3</p> <p>4-4</p> <h1>我是老马</h1> <div class = "tem" >混淆</div> <script> // 把页面中所有的p标签选择出来 // 获取当前文档中的所有p标签 var array = document.getElementsByTagName( "p" ); // 此方法返回 HTMLCollection 集合对象 是一个伪数组 // array → HTMLCollection → Object.prototype console.log( array ); // 要求吧当前页面中所有p标签的内部文字打印 for( i = 0;i < array.length;i++ ){ console.log( array[i].innerHTML ); } //伪数组变数组 var a = Array.prototype.slice.call(array,0); console.log( a ); </script> </body>
HTMLCollection
示例代码
<body> <p name = "p1">k1</p> <p name = "p2">k2</p> <div name = "dd1" class="pss1">hi div1</div> <div name = "dd1" class="pss2">hi div2</div> <div name = "dd1" class="pss3">hi div3</div> <script> // 把当前页面中所有的标签都获取来 var all = document.getElementsByTagName( "*" ); // all => HTMLCollection for( var i = 0;i < all.length;i++ ){ console.log( all[i] ); } // HTMLCollection 是动态集合 当标签发生变化的时候,HTMLCollection会自动更新同步 // HTMLCollection item() 通过索引获取标签对象 Element 同[] var a = Array.prototype.slice.call( all,0 ); console.log( a ); </script> </body>
querySelector
支持IE8及其以上版本
示例代码
<body> <div class = "c1">第一个div</div> <p class = "tm">老马的qq学习视频</p> <h3 id = "tmd">这里有好山好水好风景</h3> <script> // querySelector可以接受一个css的选择器字符串作为参数,来搜索页面中的标签元素 var element1 = document.querySelector( ".c1" ); console.dir( element1 ); var p1 = document.querySelector( ".tm" ); console.dir( p1 ); var h = document.querySelector( "#tmd" ); console.dir( h ); var p2 =document.querySelector( "p .c" ); console.dir( p2 ); //null </script> </body>
querySelectorAll案例
示例代码
<body> <p>ss1</p> <p class = "tm">ss2</p> <p class = "tm">ss3</p> <script> // querySelectorAll案例 // 把页面中所有的p标签包含tm像是类的标签选出来 var arr = document.querySelectorAll( "p.tm" ); // arr 伪数组不会自动更新 // arr 是一个NodeList接口的示例。NodeList的原型是 Object.prototype console.log( arr ); // 用forEach接收一个函数对数组中的元素进行处理 // 函数第一个参数是数组的元素,第二个参数是元素对应的索引 arr.forEach( function(elem,index){ console.log( index + ":" + elem.innerHTML ); } ); </script> </body>
NodeList对象节点集合
了解Node对象(接口)
DOM继承关系图
1.3 事件
事件的概念
元素绑定事件
第一种示例代码 不推荐
<body> <p onclick="alert('123')">前端学习</p> <input type="button" value="点击我" onclick="alert('点击了')"> </body>
上述代码分析
代码的方法对标签进行绑定事件示例代码
<body> <div id = "tm"> 前端学习视频 </div> <script> // 第一步拿到 要绑定事件的div var d = document.querySelector( "#tm" ); ///id选择器 d.onclick = function(){ alert( "123" ); }; // 事件的三个要素:1div对象 2onclick 3行为 匿名函数 //这种绑定事件的方式,只能绑定一个方法 // d.onclick = function(){ // console.log( 1 ); // }; </script> </body>
案例
示例代码
<body> <ul id="cityList"> <li>背景1</li> <li>背景2</li> <li>背景3</li> <li>背景4</li> <li>背景5</li> </ul> <script> // 第一种方法 // 给所有的li标签绑定点击事件,并且弹出li标签的内容 // 第一步,先找到所有的li标签 // var liNodeList = document.querySelectorAll( "#cityList li" ); // liNodeList.forEach(function(element,index){ // // 绑定点击事件 // element.onclick = function(){ // alert( this.innerHTML ); // }; // }); // li标签的事件响应方法都是一样的,没必要每循环一次创建一个响应事件函数对象 // 第二种方法 优化方法 var liNodeList = document.querySelectorAll( "#cityList li" ); liNodeList.forEach(function(element,index){ // 绑定点击事件响应方法 指向一个声明的函数 element.onclick = liOnClickHander; }); // li标签点击时候出发执行的事件响应方法 function liOnClickHander(){ alert( this.innerHTML ); }; </script> </body>
事件流
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>事件流</title> <style> div { border:1px solid red; } .parent { height: 200px; width: 200px; padding: 30px; background-color: pink; } .child { height: 100px; width: 100px; background-color: yellow; } </style> </head> <body> <div class="parent"> 我是父div <div class="child"> 我是子div </div> </div> <script> // 事件流 本案例会发生冒泡 // 点击了子元素标签的时候,父元素绑定的点击事件也会被执行:原因事件魔炮 // 给父元素绑定一个点击事件 点击子元素,看是否事件响应方法执行 var parentDiv = document.querySelector( ".parent" ); parentDiv.onclick = function(){ alert( "我是父div触发" ); }; window.onclick = function(){ alert( "我是window触发" ); } </script> </body> </html>
绑定事件(DOM2级)
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>addEventListener案例</title> <style> div { border:1px solid red; background-color: pink; } .parent { height: 200px; width: 200px; padding: 30px; } .child { width: 100px; height: 100px; background-color: yellow; } </style> </head> <body> <input id="btn" type="button" value="点击我"> <div class="parent"> 父亲div <div class="child"> 子div </div> </div> <script> // 拿到了按钮的DOM元素对象 var btn = document.querySelector( "#btn" ); // 第一种 DOM的绑定方式 // btn.onclick = function(){ // alert( "点击我的响应" ); // }; // 缺点: 1 不能绑定多个事件处理程序 // 2 只能在冒泡阶段执行事件响应程序 // 第二种绑定事件的方式 传递三个参数 // 第一个参数是 事件类型字符串不带on // 第二个参数是 事件处理程序 // 第三个参数是 是否在捕获阶段执行事件处理程序 btn.addEventListener("click",function(){ alert( "按钮被点击1" ); },false); // 给一个按钮的点击事件绑定了两个事件处理程序 btn.addEventListener("click",function(){ alert( "按钮被点击2" ); },false); // DOM2绑定事件的方式 事件执行顺序是注册的事件处理程序顺序 // 控制在捕获阶段执行事件的响应函数 var parentDiv = document.querySelector( ".parent" ); var childDiv = document.querySelector( ".child" ); // 捕获阶段执行事件处理程序 // parentDiv.addEventListener("click",function(){ // alert( "父div" ); // },true); // childDiv.addEventListener("click",function(){ // alert( "子div" ); // },true); // 冒泡阶段执行事件响应程序 parentDiv.addEventListener("click",function(){ alert( "父div" ); },false); childDiv.addEventListener("click",function(){ alert( "子div" ); },false); </script> </body> </html>
案例
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>五角星案例</title> <style> div { font-size:30px; cursor:pointer; } </style> </head> <body> <div class="wjx-wrap"> <span>☆</span> <span>☆</span> <span>☆</span> <span>☆</span> <span>☆</span> </div> <script> // 五角星案例 // 拿到所有的五角星的span的NodeList集合 var wjxList = document.querySelectorAll( ".wjx-wrap span" ); // // 给所有的五角星绑定点击事件 // wjxList.forEach( function(element,index){ // element.addEventListener("click",function(){ // // 先把所有的五角星设置为空心 // wjxList.forEach( function(ele,ind){ // ele.innerHTML = "☆"; // } ); // // 再把选中的五角星设置为实心 // element.innerHTML = "★"; // },false); // } ); // 循环注册事件的时候,一定要注意内存消耗的问题 wjxList.forEach( function(element,index){ element.addEventListener("click",wjxClickHandler,false); } ); // 五角星点击事件的处理程序 function wjxClickHandler(){ // 先把所有的五角星设置为空心 wjxList.forEach( function(ele,ind){ ele.innerHTML = "☆"; } ); // 再把选中的五角星设置为实心 // 在事件处理函数的 作用域中,this就指向当前注册事件的标签元素 this.innerHTML = "★"; } </script> </body> </html>
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>自动添加li标签效果</title> </head> <body> <input id="btnAdd" type="button" value="添加"> <ul class="list"> </ul> <script> // 拿到btn按钮 var btnAdd = document.querySelector( "#btnAdd" ); //ie8开始支持 var index = 1; btnAdd.addEventListener("click" ,function(){ // 拿到ul标签 var list = document.querySelector( ".list" ); list.innerHTML += "<li>" + index + "</li>"; index++; },false); //ie8都不支持 </script> </body> </html>
解除绑定事件(DOM2级)
代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>解除事件绑定</title> </head> <body> <input type="button" value="点击按钮" id="btnClick"> <input type="button" value="解除绑定事件" id="btnRemove"> <input type="button" value="按钮3" id="btn3"> <script> var btnClick = document.querySelector("#btnClick"); var btnRemove = document.querySelector("#btnRemove"); // DOM0绑定事件 btnClick.onclick = function(){ alert( "DOM0 级点击事件" ); }; // DOM2绑定事件 btnRemove.addEventListener("click",function(){ // 给btnClick按钮的DOM0事件解除绑定 btnClick.onclick = null; // 给btnClick按钮解绑DOM2级别的事件 btnClick.removeEventListener("click",btnClickHander); }); // DOM2级事件绑定和解绑 btnClick.addEventListener("click",btnClickHander); // 事件处理程序 function btnClickHander(){ alert("DOM2级的绑定事件"); } //以下方法不正确 因为两个function不是同一对象 var btn3 = document.querySelector("#btn3"); btn3.addEventListener('click',function(){ alert("3"); }); btn3.removeEventListener('click',function(){ alert("3"); }); </script> </body> </html>
IE8的事件绑定和解绑
检查命令应用的浏览器版本:https://caniuse.com/#search=addEvent
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>IE的事件绑定程序</title> </head> <body> <!-- 此案例在IE8910可以用 在chrome和ie11不能用 --> <input type="button" value="点击" id="btn"> <input type="button" value="解绑" id="btnDetach"> <script> // 获取按钮btn var btn = document.getElementById("btn"); var btnDetach = document.getElementById("btnDetach"); // 给IE浏览器绑定点击事件 btn.attachEvent( "onclick",k ); btnDetach.attachEvent("onclick",function(){ // 对IE浏览器进行解绑事件 btn.detachEvent( "onclick",k ); }); // 事件处理程序 function k(){ alert( "ok" ); } </script> </body> </html>
跨浏览器兼容绑定事件
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>事件绑定兼容处理</title> </head> <body> <input type="button" value="点击" id="btn"> <script> // 兼容ie和其他浏览器 var btn = document.querySelector("#btn"); // 所有刘浏览器都兼容DO0的注册绑定事件的方法 // btn.onclick = funtion(){ // alert("ok"); // }; // 兼容ie浏览器和其他浏览器的兼容方法 if( btn.addEventListener ){ btn.addEventListener( "click",clickHandler ); }else{ btn.attachEvent( "onclick",clickHandler ); } function clickHandler(){ alert( "兼容处理" ); } </script> </body> </html>
事件响应方法的执行顺序
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>事件注册的执行顺序</title> </head> <body> <input type="button" value="点击" id="btn"> <script> var btn = document.getElementById("btn"); // DOM0的绑定事件响应方法 btn.onclick = function(){ alert("DOM0"); }; // DOM2的绑定事件的方式 if(btn.addEventListener){ btn.addEventListener("click",function(){ alert("DOM2 1"); }); btn.addEventListener("click",function(){ alert("DOM2 2"); }); btn.addEventListener("click",function(){ alert("DOM2 3"); }); }else{ btn.attachEvent("onclick",function(){ alert("DOM2 IE 1"); }); btn.attachEvent("onclick",function(){ alert("DOM2 IE 2"); }); btn.attachEvent("onclick",function(){ alert("DOM2 IE 3"); }); } </script> </body> </html>
1.4 事件对象
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>事件对象</title> </head> <body> <input type="button" value="按钮" id="btn"> <script> var btn = document.getElementById("btn"); // DOM0绑定事件的方式,兼容性最好 btn.onclick = function(e){ // 标准浏览器,e就是事件对象 // IE浏览器中是通过window.event属性获取当前的事件对象 e = e ? e : window.event; console.dir(e); // e.target;//事件源 // e.serElement;//ie if(e.target === this){ // 判断事件是自己触发的还是冒泡来的 } }; </script> </body> </html>
阻止事件冒泡与默认行为
阻止事件冒泡
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>阻止事件冒泡</title> <style> div { height: 200px; width: 200px; border: 1px solid red; text-align: center; line-height: 200px; } </style> </head> <body> <div id="box"> <input type="button" value="子元素" id="btn"> </div> <script> var box = document.getElementById("box"), btn = document.getElementById("btn"); box.onclick = function(e){ alert("div"); }; btn.onclick = function(e){ alert("btn"); // 阻止自按钮的点击事件冒泡到父盒子的方法 e = e || window.event; if( e.stopPropagation ){ e.stopPropagation(); //标准浏览器 阻止事件冒泡 }else{ e.cancelBubble = true; //IE8及以下 阻止事件冒泡 } }; </script> </body> </html>
阻止事件捕获
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>阻止事件捕获</title> <style> div { width: 200px; height: 200px; border: 1px solid red; text-align: center; line-height: 200px; } </style> </head> <body> <div id = "pDiv"> <input type="button" value="按钮" id="btn"> </div> <script> var pDiv = document.getElementById("pDiv"); var btn = document.getElementById("btn"); pDiv.addEventListener("click",function(e){ alert("父div"); e.stopPropagation(); //阻止事件冒泡或者事件捕获 },true); btn.addEventListener("click",function(){ alert("子btn"); },true); </script> </body> </html>
阻止默认行为
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>阻止默认行为</title> </head> <body> <a id="baidu" href="http://www.baidu.com">百度</a> <script> var baidu = document.getElementById("baidu"); baidu.onclick = function(e){ // 兼容处理事件对象 e = e || window.event; // 标准浏览器 if(e.preventDefault){ e.preventDefault(); //阻止默认行为 }else{ e.returnValue = false; //兼容IE8及其以下 } return false; //返回值给一个false,也可以实现阻止默认行为 }; </script> </body> </html>
事件处理程序的返回值
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>阻止表单提交</title> </head> <body> <form action="#"> 用户名:<input type="text" name="txt" id="txtName"> <hr> <input type="submit" value="提交" id="btnSub"> </form> <script> var btnSub = document.getElementById("btnSub"); btnSub.onclick = function(e){ e = e || window.event; return false; //可以阻止表单的提交 }; </script> </body> </html>
案例
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>keypress</title> </head> <body> <input type="text" id="txt"> <hr> <input type="number" name="" id=""> <script> var txt = document.getElementById("txt"); // onkeypress事件,当 键盘上键被按下的时候回触发 txt.onkeypress = function(e){ e = e || window.event; // 事件对象中的keyCode属性就是按下的键盘上的键的编码 // console.log(e.keyCode); // 0=>48 9=>57 if( e.keyCode < 48 || e.keyCode > 57 ){ console.log( e.keyCode ); return false; } }; </script> </body> </html>
提醒用户是否离开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>提醒用户是否离开</title> </head> <body> <form action="http://www.baidu.com"> 用户名:<input type="text" name="" id=""> <hr> <input type="submit" value="提交" id=""> </form> <script> window.onbeforeunload = function(){ return "您是否要离开"; // 返回一个字符串,浏览器在跳转其他页面或者关闭的时候,会提醒用户 }; </script> </body> </html>
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>提醒用户是否离开</title> </head> <body> <form action="http://www.baidu.com"> 用户名:<input type="text" name="" id="txtName"> <hr> <input type="submit" value="提交" id="btnSub"> </form> <script> window.onbeforeunload = function(){ return "您是否要离开"; // 返回一个字符串,浏览器在跳转其他页面或者关闭的时候,会提醒用户 }; // DOM0的 var txtName = document.getElementById("txtName"); var btnSub = document.getElementById("btnSub"); // btnSub.onclick = function(){ // //取消默认操作(DOM0级中) 可以使用return false // //判断用户名的文本是否为空 // if( !txtName.value ){ // alert( "用户名不能为空" ); // return false; //所有浏览器都支持,但是只能在DOM0绑定事件中使用 // } // }; //DOM2的 if( btnSub.addEventListener ){ // 标准浏览器 btnSub.addEventListener("click",btnSubHandler,false); }else{ btnSub.attachEvent("onclick",btnSubHandler); } // 提交按钮的事件处理程序 function btnSubHandler(e){ e = e || window.event; if( !txtName.value ){ // 取消默认行为,取消表单提交 alert( "用户名不能为空" ); if(e.preventDefault){ e.preventDefault(); //标准浏览器阻止默认行为 }else{ e.returnValue = false; //IE8 } } } </script> </body> </html>
1.5 事件类型
文档加载完成事件
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>onload</title> </head> <body> <script> // 页面的内容全加载完成后,才触发此事件 window.onload = function(){ var btn = document.getElementById("btn"); btn.onclick = function(){ console.log("ok"); alert("1"); }; }; </script> <input type="button" id="btn" value="点击"> </body> </html>
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>window的加载事件优化</title> <script> // 兼容以下 标准浏览器和ie浏览器,在文档加载完成后立即绑定事件 // ie9以上才支持 // document.addEventListener('DOMContentLoaded',function(e){ // console.log("DOMContentLoaded"); // // 给按钮绑定事件 // var btn = document.getElementById("btn"); // btn.addEventListener("click",function(e){ // alert("ok"); // },false); // },false); // document.onDOMContentLoaded = function(){}; // 所有的窗口中元素都加载完成后才触发(不包括ajax请求内容) // window.onload = function(){console.log("window.onload");}; // ie8 文档加载完成后就立即绑定dom事件 // document.onreadystatechange = function(e){ // console.log(document.readyState); // if( document.readyState == "interactive" ){ // var btn = document.getElementById("btn"); // btn.onclick = function(){ // alert("ok"); // }; // } // }; // jQuery 实现文档加载完成后事件的原理 document.myReady = function( callback ){ // 封装标准浏览器和ie浏览器 if( document.addEventListener ){ document.addEventListener("DOMContentLoaded",callback,false); }else if(document.attachEvent){ // 兼容IE8及以下的浏览器 document.attachEvent("onreadystatechange",function(){ // 文档的状态为interactive表示,文档dom对象可以进行访问 if(document.readyState == "interactive"){ callback(window.event); } }); }else{ // 其他特殊情况 window.onload = callback; } }; document.myReady(function(e){ // 注册事件 var btn = document.getElementById("btn"); btn.onclick = function(){ alert("ok2"); }; }); </script> </head> <body> <input type="button" value="按钮" id="btn"> </body> </html>
窗口事件
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>onscroll</title> </head> <body> <h1>1</h1> <h1>2</h1> <h1>3</h1> <h1>4</h1> <h1>5</h1> <h1>6</h1> <h1>7</h1> <h1>8</h1> <h1>9</h1> <h1>10</h1> <h1>11</h1> <h1>12</h1> <h1>13</h1> <h1>14</h1> <h1>15</h1> <h1>16</h1> <h1>17</h1> <h1>18</h1> <h1>19</h1> <h1>20</h1> <h1>21</h1> <h1>22</h1> <h1>23</h1> <h1>24</h1> <h1>25</h1> <script> // scroll 事件会进行重复触发 window.onscroll = function(e){ console.log("scroll"); console.log(window.pageYOffset); // window.pageXOffset //都是标准浏览器才有的 // ie不支持pageXOffset pageYOffset console.log(document.documentElement.scrollTop || document.body.scrollTop); // ie支持 标准浏览器支持 }; </script> </body> </html>
滚动案例1
示例代码 滚动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>滚动案例</title> <script src="../js/documentReady.js"></script> <script> document.myReady(function(){ window.onscroll = function(){ // 拿到滚动的距离 var scrollH = document.documentElement.scrollTop || document.body.scroll; // 拿到整个网页的高度 var pageH = document.body.clientHeight; // 拿到整个窗口的高度 var viewportH = document.documentElement.clientHeight; // 底部的高度 = 整个网页高度 - 滚动高度 - 窗口高度 var bottomH = pageH - scrollH - viewportH; if( bottomH < 50 ){ var list = document.getElementById("list"); var tempstr = ""; for( var i=0;i < 10;i++ ){ tempstr += "<li>"+ new Date() +"</li>"; } list.innerHTML += tempstr; } }; }); </script> </head> <body> <ul id="list"> <li> <h1>1</h1> </li> <li> <h1>2</h1> </li> <li> <h1>3</h1> </li> <li> <h1>4</h1> </li> <li> <h1>5</h1> </li> <li> <h1>6</h1> </li> <li> <h1>7</h1> </li> <li> <h1>8</h1> </li> <li> <h1>9</h1> </li> <li> <h1>10</h1> </li> <li> <h1>11</h1> </li> <li> <h1>12</h1> </li> <li> <h1>13</h1> </li> <li> <h1>14</h1> </li> <li> <h1>15</h1> </li> <li> <h1>16</h1> </li> <li> <h1>17</h1> </li> <li> <h1>18</h1> </li> <li> <h1>19</h1> </li> <li> <h1>20</h1> </li> <li> <h1>21</h1> </li> <li> <h1>22</h1> </li> <li> <h1>23</h1> </li> <li> <h1>24</h1> </li> <li> <h1>25</h1> </li> <li> <h1>26</h1> </li> <li> <h1>27</h1> </li> <li> <h1>28</h1> </li> <li> <h1>29</h1> </li> <li> <h1>30</h1> </li> <li> <h1>31</h1> </li> <li> <h1>32</h1> </li> <li> <h1>33</h1> </li> <li> <h1>34</h1> </li> <li> <h1>35</h1> </li> <li> <h1>36</h1> </li> <li> <h1>37</h1> </li> <li> <h1>38</h1> </li> <li> <h1>39</h1> </li> <li> <h1>40</h1> </li> </ul> </body> </html>
滚动案例2 滚动到某个位置固定定位
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>hao123页面滚动固定定位</title> <style> body,div,h1 { padding: 0; margin:0; } .top-wrap { height: 150px; background-color: pink; } .top-logo-wrap { height: 50px; background-color: green; } .top-search-wrap { height: 100px; width: 100%; background-color: yellowgreen; } .top-search-wrap-fixed { position: fixed; top:0; left: 0; } </style> <script src="../js/documentReady.js"></script> <script> document.myReady(function(){ // 当页面滚动到50像素的时候 让搜索的div进行固定定位 var searchBox = document.getElementById("searchBox"); window.onscroll = function(){ // 拿到滚动的距离 var scrollH = document.documentElement.scrollTop || document.body.scrollTop; if( scrollH > 50 ){ // 让搜索的div设置上样式 top-search-wrap-fixed searchBox.className ="top-search-wrap top-search-wrap-fixed"; } else { searchBox.className ="top-search-wrap"; } }; }); </script> </head> <body> <div class = "top-wrap"> <div class="top-logo-wrap">可以卷进去的顶部</div> <div id="searchBox" class="top-search-wrap">固定定位的</div> </div> <h1>1</h1> <h1>2</h1> <h1>3</h1> <h1>4</h1> <h1>5</h1> <h1>6</h1> <h1>7</h1> <h1>8</h1> <h1>9</h1> <h1>10</h1> <h1>11</h1> <h1>12</h1> <h1>13</h1> <h1>14</h1> <h1>15</h1> <h1>16</h1> <h1>17</h1> <h1>18</h1> <h1>19</h1> <h1>20</h1> </body> </html>
焦点事件
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>焦点事件</title> </head> <body> <input type="text" name="" id="txt1"> <input type="text" name="" id="txt2"> <input type="button" value="txt2获得焦点" id="btnFocus2"> <script> window.onload = function(){ var txt1 = document.getElementById("txt1"); txt1.onfocus = function(){ console.log("获得焦点"); }; txt1.onblur = function(){ console.log("失去焦点"); }; var btnFocus2 = document.getElementById("btnFocus2"); .onclick = function(){ // 通过js代码设置文本框获得 焦点 document.getElementById("txt2").focus(); }; }; </script> </body> </html>
焦点事件案例
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>焦点事件</title> </head> <body> <input type="text" name="" id="txt1"> <input type="text" name="" id="txt2"> <input type="button" value="txt2获得焦点" id="btnFocus2"> <script> window.onload = function(){ var txt1 = document.getElementById("txt1"); txt1.onfocus = function(){ console.log("获得焦点"); }; txt1.onblur = function(){ console.log("失去焦点"); }; var btnFocus2 = document.getElementById("btnFocus2"); btnFocus2.onclick = function(){ // 通过js代码设置文本框获得 焦点 document.getElementById("txt2").focus(); }; // 要实现:文本框 2 不能为空 var txt2 = document.getElementById("txt2"); txt2.onblur = function(){ // 判断文本框2的value属性是否为空 if( txt2.value == "" ){ // 如果为空 ,则让文本框2继续获得焦点 txt2.focus(); // 让文本框的边框设置为红色 txt2.style.borderColor = "red"; }else{ txt2.style.borderColor = ""; } }; }; </script> </body> </html>
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文本框显示案例</title> </head> <body> <input type="text" placeholder="老马" id=""> <input type="text" value="老马" id="txt2"> <script> window.onload = function(){ var txt2 = document.getElementById("txt2"); // 文档加载完成后,直接设置提示文本为灰色 txt2.style.color = "#ccc"; // 文本框2 获得焦点时候,判断文本框值是否等于老马,如果是清空 txt2.onfocus = function(){ if( txt2.value == "老马" ){ txt2.value = ""; txt2.style.color = "#000"; } }; // 文本框2 离开加点的时候,判断文本框的值是否为空,空则设置回老马 txt2.onblur = function(){ if( txt2.value == "" ){ txt2.value = "老马"; txt2.style.color = "#ccc"; } }; }; </script> </body> </html>
文本框弹出提示选择框案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文本框弹出提示选择案例</title> <style> html,body,div,ul,li,input { margin: 0; padding:0; } ul { list-style: none; } .search-box-wrap { margin:0 auto; width: 300px; height: 400px; padding-top:30px; position: relative; } .search-box-wrap .list{ border: 1px solid #ddd; width:198px; display: none; position: absolute; } .search-box-wrap .list li{ height: 25px; line-height: 25px; padding-left: 5px; } .search-box-wrap .list li:hover { background-color: #eee; cursor: pointer; } .txt-search { border-width: 2px; width: 191px; height: 20px; padding-left: 5px; line-height: 20px; } </style> </head> <body> <div class="search-box-wrap"> <input type="text" id="txtSearch" class="txt-search"> <ul class="list" id="tipList"> <li>老马1</li> <li>老马2</li> <li>老马3</li> <li>老马4</li> <li>老马5</li> </ul> </div> <script> // 当文本框获得焦点,提示框显示,失去焦点,提示框关闭 (function(){ // 模拟的块级作用域,不会影响全局的变量 window.onload = function(){ var txtSearch = document.getElementById("txtSearch"); var tipList = document.getElementById("tipList"); var liList = tipList.getElementsByTagName("li"); txtSearch.onfocus = function(){ // 弹出提示框 tipList.style.display = "block"; // 弹出的提示框,不能影响原来的流式布局 }; txtSearch.onblur = function(){ tipList.style.display = "none"; // 关闭提示框 }; // 给所有li绑定点击事件,实现li点击后,把li上的文本放到文本框上去 for( var i=0;i < liList.length; i++ ){ liList[i].onmousedown = tipLiHandler; // 点击事件和失去焦点事件执行循序 // 第一步 先执行mousedown事件 事件中,慧然被点击的元素获得焦点, // 那么原来获得焦点的元素失去焦点 // mousedown → 原来获得焦点元素blur事件 → 当前元素的mouseup → click事件执行 // 如果mousedown事件中,阻止默认行为,那么此元素就不会获得焦点 } // 所有li标签点击事件的绑定的事件处理程序,减少内存消耗 function tipLiHandler(){ var txt = this.innerHTML; // this = = = liList[i] txtSearch.value = txt; // 把li标签的文本设置到文本框上去 } }; })(); </script> </body> </html>
1.6 鼠标事件
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>鼠标事件的区别</title> <style> div { border: 1px solid #ccc; } p { margin:20px; border:1px solid red; } </style> </head> <body> <div class="box" id="box"> <p>我观看的是老马视频</p> <p>我观看的是老马视频</p> <p>我观看的是老马视频</p> <p>我观看的是老马视频</p> <p>我观看的是老马视频</p> </div> <script> // document.onDOMContentLoaded = function(){}; // document.onreadystatechange = function(){}; (function(){ window.onload =function(){ var box = document.getElementById("box"); box.onmousedown = function(){ console.log("mousedown"); // 最先实行 }; box.onmouseup = function(){ // 其次执行 console.log("mouseup"); }; // 如果鼠标不是当前元素上up 那么就不会触发click box.onclick = function(){ console.log("click"); }; // 当鼠标进入元素范围后,只执行一次,不会冒泡 box.onmouseenter = function(){ console.log("enter"); }; // 离开元素范围后,只执行一次,不会冒泡 box.onmouseleave = function(){ console.log("leave"); }; // 在元素或者子元素上面的时候回触发,回冒泡 box.onmouseover = function(e){ console.log("over"); }; // 离开子元素或者自身的时候回触发,回冒泡; box.onmouseout = function(e){ console.log("out"); }; }; })(); </script> </body> </html>
鼠标事件对象(接口)
鼠标事件对象的坐标位置
案例
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>E41-蝴蝶跟随鼠标飞案例.html</title> <style> html,body { padding: 0px; margin:0px; } img { position: absolute; } </style> </head> <body> <img id="imgB" src="./a.gif" alt="蝴蝶" width="50px" height="50px"> <script> (function(){ window.onload = function(){ // 给整个文档添加一个mousemove事件 document.onmousemove = function(e){ //鼠标的事件对象 e = e || window.event; // 获得鼠标移动的位置所在整个页面的坐标 // var = e.pageX; // var = e.pageY; var pageX = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft); var pageY = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop); // 给固定定位的图片设置left和top值 var imgB = document.getElementById("imgB"); imgB.style.left = pageX - 25 + "px"; imgB.style.top = pageY - 25 + "px"; }; }; })(); </script> </body> </html>
拖动div案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>div的拖动案例</title> <style> html,body,div { margin:0; padding:0; } body{ background-color: silver; } .box { position: absolute; width: 100px; height: 100px; background-color: red; border: 1px solid yellow; cursor: move; } </style> </head> <body> <div id="box" class="box" style="left:200px;top:150px;"></div> <script> // 监听div:mousedown 开始计算鼠标移动的位移,通过鼠标位移水平方向位置设置div的left // 通过计算鼠标垂直方向移动的位移,来设置div的top值 // 如果div mouseup触发了 那么计算和移动div就结束 // mousedown的时候,设置标志位true开始移动div mouseup的时候,设置标志位为false // 停止移动div,mousemove的时候,记录当前的位置和上一次mousemove的位置坐移动距离的计算,并移动div (function(){ // 移动标志 var isMove = false; var box = document.getElementById("box"); //定义鼠标移动的上一个页面坐标 var tempX = 0, tempY = 0; // 鼠标按下,开始移动div box.onmousedown = function(e){ isMove = true; e = e || window.event; // 当鼠标点下去的时候,设置第一个鼠标上一次移动的位置 tempX = e.clientX + ( document.documentElement.scrollLeft || document.body.scrollLeft ); tempY = e.clientY + ( document.documentElement.scrollTop || document.body.scrollTop ); }; // 鼠标抬起,停止移动div box.onmouseup = function(e){ isMove = false; }; // mousemove的时候移动div document.onmousemove =function(e){ // 只有鼠标点下去的时候,才做移动处理 if(!isMove){ return; } // 计算出当前坐标的位置 // screenX screenY clientX clientY 滚动问题 // pageX pageY e = e || window.event; // 下面是鼠标相对于页面的x 和 y 坐标 var pageX = e.clientX + ( document.documentElement.scrollLeft || document.body.scrollLeft ); var pageY = e.clientY + ( document.documentElement.scrollTop || document.body.scrollTop ); // 移动距离 var xH = pageX - tempX; var yH = pageY - tempY; console.log("xH:" + xH + " yH:" + yH); // 要把移动的div,在x方向,移动xH 在y方向上移动yH // 设置元素的style.left style.top // 一开始如果没有通过js设置style.left 和 style.top 那么值都为"" // js是拿不到css设置的left和top // js指定能控制标签的style属性,并且可以读取标签的style属性中的top和left box.style.left = ( parseFloat(box.style.left) + xH) + "px"; box.style.top = ( parseFloat(box.style.top) + yH) + "px"; // 为鼠标下一次mousemove事件计算初始化鼠标位置 tempX = pageX; tempY = pageY; }; })(); </script> </body> </html>
鼠标事件对象的鼠标按钮信息 onmousedown
鼠标键的兼容处理
案例
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>自定义右键菜单</title> <style> html,body,h1,ul,li { padding:0; margin:0; } ul { list-style: none; } .menu { position: absolute; background-color: #fff; border:1px solid red; display: none; } .menu .menu-item { border:1px solid #000; cursor: pointer; padding:5px; } .menu .menu-item:hover { background-color: #aaa; } </style> </head> <body> <h1 id="hTitle">我学习的老马前端</h1> <ul class="menu" id="menuList"> <li class="menu-item" >老马1</li> <li class="menu-item" >老马2</li> <li class="menu-item" >老马3</li> <li class="menu-item" >老马4</li> <li class="menu-item" ><a href="http://www.baidu.com" target="_blank">老马5</a></li> </ul> <script> ;(function(){ window.onload = function(){ // 获取h1标签 var hTitle = document.getElementById( "hTitle" ); var menuList = document.getElementById( "menuList" ); // 给标签添加鼠标按下的事件 hTitle.onmousedown = function(e){ e = e || window.event; // e.button // 获得你点击时那个鼠标按钮 if( e.button == 2 || e.button == 6 ){ // console.log( "右键点击了" ); // 弹出我们自定义的右键菜单 menuList.style.display = "block"; // 控制弹出来的菜单的位置为鼠标的位置 // 获取鼠标的位置 var pageX = e.clientX + ( document.documentElement.scrollLeft || document.body.scrollLeft ); var pageY = e.clientY + ( document.documentElement.scrollTop || document.body.scrollTop ); menuList.style.left = pageX + "px"; menuList.style.top = pageY + "px"; } }; // 点击文档,关闭右键弹出来的菜单 document.onclick =function(e){ menuList.style.display = "none"; }; // 在真个文档中屏蔽浏览器默认的右键菜单 document.oncontextmenu = function(e){ // 阻止默认行为就可以阻止浏览器弹出右键菜单 e = e || window.event; if( e.preventDefault ){ e.preventDefault(); }else{ e.returnValue = false; } return false; }; }; })(); </script> </body> </html>
鼠标事件对象的键盘信息
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>单选多选段落按钮</title> <style> .pBox p{ cursor: pointer; } </style> </head> <body> <div id="pBox"> <p>我是段落1</p> <p>我是段落2</p> <p>我是段落3</p> <p>我是段落4</p> <p>我是段落5</p> </div> <script> ;(function(){ window.onload = function(){ var pBox = document.getElementById( "pBox" ); // 拿到所有的p标签都绑定点击事件 // 或去所有的p标签,pList是一个伪数组 var pList = pBox.getElementsByTagName("p"); for( var i=0;i < pList.length;i++ ){ pList[i].onclick = pClickHandler; } }; // 段落标签点击的事件处理程序 function pClickHandler(e){ e = e || window.event; //判断是否按下了键盘的ctrl键 if( e.ctrlKey ){ // 多选 this.style.backgroundColor = "silver"; }else{ // 单选 var pBox = document.getElementById( "pBox" ); // 拿到所有的p标签都绑定点击事件 // 或去所有的p标签,pList是一个伪数组 var pList = pBox.getElementsByTagName("p"); for( var i=0;i < pList.length;i++ ){ pList[i].style.backgroundColor = "#fff"; } this.style.backgroundColor = "silver"; } } })(); </script> </body> </html>
1.7 键盘和文本事件
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>键盘事件</title> <script src="../js/documentReady.js"></script> </head> <body> <input type="text" name="" id="txt"> <script> ;(function(){ document.myReady(function(){ // 可以进行绑定事件 var txt = document.getElementById("txt"); // 键盘上的键只要被按下 就会触发keydown事件 // keydown可以应用于所有的dom对象,比如p标签,div标签 // 可以监听到功能键的按下事件 比如ctrl shift alt 方向键 f1 esc // 如果一直按着键不放开,那么会一直触发 txt.onkeydown = function(e){ e = e || window.event; console.log( "keydown==> keyCode:" + e.keyCode + " charCode:" + e.charCode ); }; // 可以一直触发事件,智能监听,可打印的 字符键 退格键就不行 // keypress事件是区分按下是大写字符和小写字符 txt.onkeypress = function(e){ e = e || window.event; console.log( "keyPress==> keyCode:" + e.keyCode + " charCode:" + e.charCode ); }; // 与keydown一样,不区分大小写,按下的一律按照大写字母的编码计算 txt.onkeyup = function(e){ e = e || window.event; console.log( "keyUp==> keyCode:" + e.keyCode + " charCode:" + e.charCode ); }; }); })(); </script> </body> </html>
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文本框获得焦点案例</title> <script src="../js/documentReady.js"></script> </head> <body> <div id="wrap"> <div id="box"> <input type="text" name="" id="txt1"> <input type="text" name="" id="txt2"> <input type="text" name="" id="txt3"> </div> <input type="button" value="提交" id="btn"> </div> <script> ;(function(){ document.myReady(function(){ // 页面加载完成后执行 // 首先获取所有的input标签 绑定keyup是按 var box = document.getElementById("box"); var inputList = box.getElementsByTagName("input ); for( var i = 0;i < inputList.length;i++ ){ (function(j){ inputList[j].onkeyup = function(e){ // 检测文本框输入的文本是否达到了三个字符的长度,达到三个就让下一个文本框获取焦点的 if( this.value.length >= 3 ){ // 让下一个文本框获得焦点 if( j<=1 ){ inputList[j+1].focus(); }else{ document.getElementById("btn").focus(); } } } })(i); } }); })(); </script> </body> </html>
文本框change事件示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文本框change事件</title> <script src="../js/documentReady.js"></script> </head> <body> 用户名<input type="text" name="" id="txtName"> <input type="button" value="提交" id=""> <script> ;(function(){ document.myReady(function(){ var txtName = document.getElementById("txtName"); txtName.onchange = function(e){ // 判断一下文本框的长度为6-8 如果不是,提醒用户,并让当前文本框继续获得焦点 if( this.value.length > 8 || this.value.length < 6 ){ alert("用户名必须6-8个字符"); this.focus(); } }; }); })(); </script> </body> </html>
1.8 事件高级
封装
EventUtil.js
// 事件封装 (function(window){ // 第一个:封装绑定事件的兼容处理 var EventUtil = { // 1给谁绑定 2绑定设么事件 3绑定事件的处理程序 4捕获冒泡 addEvent:function( element,type,handler,isCapture ){ if( element.addEventListener ){ // 标准浏览器的绑定事件 // 处理四个参数,保证isCapture一定是boolean类型的 isCapture = isCapture ? true : false; element.addEventListener( type, handler, isCapture ); }else if( element.attachEvent ){ // ie8的事件绑定方法 element.attachEvent( "on"+type,function(){ // window.event return handler.call( element,window.event ); //函数调用模式 // 所有的事件处理中 this === target.event || event.scrElement } ); } }, // 获取事件对象 兼容处理 getEvent:function(e){ return e || window.event; }, // 获取事件源对象 getTarget:function(e){ return e.target || e.srcElement; }, // 阻止事件冒泡 stopPropagation:function(e){ if( e.stopPropagation ){ e.stopPropagation(); }else{ e.cancleBubble = true; } }, // 阻止默认行为 preventDefault:function(e){ if( e.preventDefault ){ e.preventDefault(); }else{ e.returnValue = false; } } }; // 把我们上面定义的对象赋值给window的属性 window.EventUtil = EventUtil; })(window || {}); // 自执行函数
documentReady.js
// jQuery 实现文档加载完成后事件的原理 /** * * @param {*} callback * 页面文档加载完成后的回调函数 */ document.myReady = function( callback ){ // 封装标准浏览器和ie浏览器 if( document.addEventListener ){ document.addEventListener("DOMContentLoaded",callback,false); }else if(document.attachEvent){ // 兼容IE8及以下的浏览器 document.attachEvent("onreadystatechange",function(){ // 文档的状态为interactive表示,文档dom对象可以进行访问 if(document.readyState == "interactive"){ callback(window.event); } }); }else{ // 其他特殊情况 window.onload = callback; } };
事件高级封装
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>事件高级封装</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <input type="button" value="提交" id="btn"> <script> (function () { document.myReady(function () { // 拿到按钮 var btn = document.getElementById("btn"); EventUtil.addEvent(btn, "click", function (e) { console.log(e); console.log(this == btn); alert("ok"); });// addEvent });//myReady })();//自执行函数 </script> </body> </html>
事件委托案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>事件委托案例</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <ul class="list" id="list" > <li>老马1</li> <li>老马2</li> <li>老马3</li> <li>老马4</li> <li>老马5</li> <li>老马6</li> <li>老马7</li> <li>老马8</li> <li>老马9</li> <li>老马10</li> <li>老马11</li> <li>老马12</li> <li>老马13</li> <li>老马14</li> <li>老马15</li> <li>老马16</li> <li>老马17</li> <li>老马18</li> <li>老马19</li> <li>老马20</li> </ul> <script> // list中的li标签个数是不确定的,也可能动态添加,也可能动态减少 // li的标签非常多,可能达到100个 (function(){ document.myReady(function(){ //拿到所有的li标签,绑定点击事件 var ulList = document.getElementById("list"); var liList = ulList.getElementsByTagName("li"); //问题 //1 动态添加li标签,是没有绑定上事件处理程序 // for( var i=0;i < liList.length;i++ ){ // EventUtil.addEvent( liList[i],"click",function(e){ // alert(this.innerHTML); // } ); // } // 2li的标签非常多的时候,产生很多都绑定事件的信息,浪费大量的内存空间和cpu计算 // 解决以上的问题 // 1 事件是有冒泡的 // 2 弹出事件源对象的内容 e.target || e.scrElement // 3 getElementByTagName方法返回的伪数组是一个动态的,自动更新 // 解决思路,子元素的事件,委托父容器来进行注册和处理 window.EventUtil.addEvent( ulList,"click",function(e){ // 子元素被点击的时候,也会冒泡到这来 var target = EventUtil.getTarget(e); // 如果是点击了父容器自己,那么就设么也不干 if( target == ulList ){ return ; } // 如果点击的是子元素 alert( target.innerHTML ); } ); }); })(); </script> </body> </html>
1.9 节点操作
节点层次
文档结构树
DOM继承关系图
Node接口
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>节点操作</title> <style> #lis { display: none; } </style> </head> <body> <ul id="list"> <li>1</li> <li>2</li> <li id="lis">3</li> <li>4</li> <li>5</li> </ul> <script> ;(function(){ window.onload = function(){ var list = document.getElementById("list"); console.log( "nodeType ==>" + list.nodeType ); console.log( "nodeName ==>" + list.nodeName ); console.log( "nodeValue ==>" + list.nodeValue ); console.log( "innerHTML ==>" + list.innerHTML ); console.log( "innerText ==>" + list.innerText ); console.log( "textContent ==>" + list.textContent ); }; })(); </script> </body> </html>
结果
Node接口
节点关系
示例代码
略
节点操作
Node的接口方法
节点操作
节点操作案例
示例代码 第一种
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>动态创建菜单案例</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <ul id="menu" > </ul> <script> // 数据: var data = [ {name:'首页', url:'/index.html', id: 1}, {name:'关于', url:'/about.html', id: 2}, {name:'产品', url:'/product.html', id: 3}, {name:'案例', url:'/usecase.html', id: 4}, {name:'联系', url:'/contact.html', id: 5} ]; // 页面加载完成后动态加载标签数据 document.myReady(function(){ loadMenu(); //初始化菜单数据 }); //加载数据菜单 function loadMenu(){ // 获得ul var menu = document.getElementById("menu"); // {name:'首页', url:'/index.html', id: 1}, // ==> <li id="menu1"><a href="/index.html">首页</a></li> for( var i=0;i < data.length;i++ ){ // 创建li标签节点 var liElement = document.createElement("li"); // 给li设置id属性 liElement.setAttribute( "id","menu" + data[i].id ); // 创建a标签 var menuLinkElement = document.createElement("a"); // 给a设置超链接属性 menuLinkElement.setAttribute("href",data[i].url); // menuLinkElement.innerHTML = data[i].name; //所有浏览器兼容 // 设置内容 if( menuLinkElement.textContent ){ menuLinkElement.textContent = data[i].name; }else{ menuLinkElement.innerText = data[i].name; } // 把a标签加到li标签下 liElement.appendChild( menuLinkElement ); // 把li标签加到ul标签中去 menu.appendChild( liElement ); } } </script> </body> </html>
示例代码 第二种
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>动态创建菜单案例</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <ul id="menu"> </ul> <script> ; (function () { // 数据: var data = [ { name: '首页', url: '/index.html', id: 1 }, { name: '关于', url: '/about.html', id: 2 }, { name: '产品', url: '/product.html', id: 3 }, { name: '案例', url: '/usecase.html', id: 4 }, { name: '联系', url: '/contact.html', id: 5 } ]; // 页面加载完成后动态加载标签数据 document.myReady(function () { loadMenuData(); //初始化菜单数据 }); function loadMenuData(){ var menu = document.getElementById("menu"); var strArray = []; // 使用innerHTML的方法直接拼接字符串 // 动态创建li标签 // <li id="menu1"><a href="/index.html">首页</a></li> for( var i=0;i < data.length;i++ ){ var str = '<li id="' + 'menu' + data[i].id + '">'; str += '<a href="' + data[i].url + '">' + data[i].name + '</a>'; str += "</li>" ; // menu.innerHTML += str;// 每创建一次li标签都会使得dom更新一次 // 效率太低,把措辞跟dom的交互编程一次 strArray.push( str ); } menu.innerHTML = strArray.join(""); } })(); </script> </body> </html>
动态创建标签的方式及注意事项
案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>关闭消息框案例</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> <style> #msgBox { width: 200px; height: 200px; border:1px solid red; position: absolute; } #msgCloseBtn { width: 50px; height: 18px; position:absolute; right: 5px; top:5px; background: url("../imgs/close2.png"); cursor: pointer; } </style> </head> <body> <div id="msgBox"> <div id="msgCloseBtn"> </div> 广告信息 </div> <script> ;(function(){ document.myReady(function(){ var msgBoxBtn = document.getElementById("msgCloseBtn"); EventUtil.addEvent(msgBoxBtn,"click",function(e){ this.parentNode.style.display = "none"; }); }); })(); </script> </body> </html>
1.10 元素样式操作
1.11 HTMLElement元素
HTML元素的大小和位置
表单操作
HTMLInputElement对象的方法和属性
示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>表单操作</title> </head> <body> <div id="box"> <input type="text" name="" id=""> <input type="text" name="" id=""> <input type="text" value="22" id=""> <input type="text" name="" id=""> <input type="text" name="" id=""> <input type="radio" name="se" id="se1"> <label for="se1">选择1</label> <input type="radio" name="se" id="se2"> <label for="se2">选择2</label> </div> <script> ;(function(){ window.onload = function(){ var box = document.getElementById("box"); var inputList = box.getElementsByTagName("input"); inputList[2].onclick = function(){ alert(this.value); }; }; })(); </script> </body> </html>
HTMLFormElement接口 表单
HTMLSelectElement接口
HTMLOptionElement
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>动态创建下拉列表</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <select name="sel" id="sel"> </select> <script> ;(function(){ // data var data = [ {name:"北京",value:1}, {name:"上海",value:2}, {name:"天津",value:4}, {name:"重庆",value:4} ]; document.myReady(function(){ // 初始化下拉列表的数据 initSel(data); }); // 初始化下拉列表 function initSel(data){ var sel = document.getElementById("sel"); for( var i=0;i < data.length;i++ ){ var opt = document.createElement("option"); opt.value = data[i].value; // opt.setAttribute("value",data[i].value); opt.text = data[i].name; // opt.innerHTMTL = data[i].name if( opt.textContent ){ opt.textContent = data[i].name; }else{ opt.innerHTML = data[i].name; } // sel.add(opt,null); sel.appendChild(opt); } } })(); </script> </body> </html>
select change的示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>动态创建下拉列表</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <select name="sel" id="sel"> </select> <script> ;(function(){ // data var data = [ {name:"北京",value:1}, {name:"上海",value:2}, {name:"天津",value:4}, {name:"重庆",value:4} ]; document.myReady(function(){ // 初始化下拉列表的数据 initSel(data); // 给下拉列表绑定change事件 var sel = document.getElementById("sel"); EventUtil.addEvent(sel,"change",function(){ // 拿到选中的选项的valueh和text var selOpt = this.options[this.selectedIndex]; console.log( selOpt.value ); console.log( selOpt.text ); // 如果只要value的值 // 直接通过select标签的value属性就可以拿到 console.log( this.value ); }); }); // 初始化下拉列表 function initSel(data){ var sel = document.getElementById("sel"); for( var i=0;i < data.length;i++ ){ var opt = document.createElement("option"); opt.value = data[i].value; // opt.setAttribute("value",data[i].value); opt.text = data[i].name; // opt.innerHTMTL = data[i].name if( opt.textContent ){ opt.textContent = data[i].name; }else{ opt.innerHTML = data[i].name; } // sel.add(opt,null); sel.appendChild(opt); } } })(); </script> </body> </html>
案例
省市选择案例示例代码(支持ie8及以上)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>省市选择案例</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <select name="" id="pro"></select> <select name="" id="city"></select> <script> // 数据 var data = [{ name: "北京", cities: ["西城", "东城", "崇文", "宣武", "朝阳", "海淀", "丰台", "石景山", "门头沟", "房山", "通州", "顺义", "大兴", "昌平", "平谷", "怀柔", "密云", "延庆"] }, { name: "天津", cities: ["青羊", "河东", "河西", "南开", "河北", "红桥", "塘沽", "汉沽", "大港", "东丽", "西青", "北辰", "津南", "武清", "宝坻", "静海", "宁河", "蓟县", "开发区"] }, { name: "河北", cities: ["石家庄", "秦皇岛", "廊坊", "保定", "邯郸", "唐山", "邢台", "衡水", "张家口", "承德", "沧州", "衡水"] }, { name: "山西", cities: ["太原", "大同", "长治", "晋中", "阳泉", "朔州", "运城", "临汾"] }, { name: "内蒙古", cities: ["呼和浩特", "赤峰", "通辽", "锡林郭勒", "兴安"] }, { name: "辽宁", cities: ["大连", "沈阳", "鞍山", "抚顺", "营口", "锦州", "丹东", "朝阳", "辽阳", "阜新", "铁岭", "盘锦", "本溪", "葫芦岛"] }, { name: "吉林", cities: ["长春", "吉林", "四平", "辽源", "通化", "延吉", "白城", "辽源", "松原", "临江", "珲春"] }, { name: "黑龙江", cities: ["哈尔滨", "齐齐哈尔", "大庆", "牡丹江", "鹤岗", "佳木斯", "绥化"] }, { name: "上海", cities: ["浦东", "杨浦", "徐汇", "静安", "卢湾", "黄浦", "普陀", "闸北", "虹口", "长宁", "宝山", "闵行", "嘉定", "金山", "松江", "青浦", "崇明", "奉贤", "南汇"] }, { name: "江苏", cities: ["南京", "苏州", "无锡", "常州", "扬州", "徐州", "南通", "镇江", "泰州", "淮安", "连云港", "宿迁", "盐城", "淮阴", "沐阳", "张家港"] }, { name: "浙江", cities: ["杭州", "金华", "宁波", "温州", "嘉兴", "绍兴", "丽水", "湖州", "台州", "舟山", "衢州"] }, { name: "安徽", cities: ["合肥", "马鞍山", "蚌埠", "黄山", "芜湖", "淮南", "铜陵", "阜阳", "宣城", "安庆"] }, { name: "福建", cities: ["福州", "厦门", "泉州", "漳州", "南平", "龙岩", "莆田", "三明", "宁德"] }, { name: "江西", cities: ["南昌", "景德镇", "上饶", "萍乡", "九江", "吉安", "宜春", "鹰潭", "新余", "赣州"] }, { name: "山东", cities: ["青岛", "济南", "淄博", "烟台", "泰安", "临沂", "日照", "德州", "威海", "东营", "荷泽", "济宁", "潍坊", "枣庄", "聊城"] }, { name: "河南", cities: ["郑州", "洛阳", "开封", "平顶山", "濮阳", "安阳", "许昌", "南阳", "信阳", "周口", "新乡", "焦作", "三门峡", "商丘"] }, { name: "湖北", cities: ["武汉", "襄樊", "孝感", "十堰", "荆州", "黄石", "宜昌", "黄冈", "恩施", "鄂州", "江汉", "随枣", "荆沙", "咸宁"] }, { name: "湖南", cities: ["长沙", "湘潭", "岳阳", "株洲", "怀化", "永州", "益阳", "张家界", "常德", "衡阳", "湘西", "邵阳", "娄底", "郴州"] }, { name: "广东", cities: ["广州", "深圳", "东莞", "佛山", "珠海", "汕头", "韶关", "江门", "梅州", "揭阳", "中山", "河源", "惠州", "茂名", "湛江", "阳江", "潮州", "云浮", "汕尾", "潮阳", "肇庆", "顺德", "清远"] }, { name: "广西", cities: ["南宁", "桂林", "柳州", "梧州", "来宾", "贵港", "玉林", "贺州"] }, { name: "海南", cities: ["海口", "三亚"] }, { name: "重庆", cities: ["渝中", "大渡口", "江北", "沙坪坝", "九龙坡", "南岸", "北碚", "万盛", "双桥", "渝北", "巴南", "万州", "涪陵", "黔江", "长寿"] }, { name: "四川", cities: ["成都", "达州", "南充", "乐山", "绵阳", "德阳", "内江", "遂宁", "宜宾", "巴中", "自贡", "康定", "攀枝花"] }, { name: "贵州", cities: ["贵阳", "遵义", "安顺", "黔西南", "都匀"] }, { name: "云南", cities: ["昆明", "丽江", "昭通", "玉溪", "临沧", "文山", "红河", "楚雄", "大理"] }, { name: "西藏", cities: ["拉萨", "林芝", "日喀则", "昌都"] }, { name: "陕西", cities: ["西安", "咸阳", "延安", "汉中", "榆林", "商南", "略阳", "宜君", "麟游", "白河"] }, { name: "甘肃", cities: ["兰州", "金昌", "天水", "武威", "张掖", "平凉", "酒泉"] }, { name: "青海", cities: ["黄南", "海南", "西宁", "海东", "海西", "海北", "果洛", "玉树"] }, { name: "宁夏", cities: ["银川", "吴忠"] }, { name: "新疆", cities: ["乌鲁木齐", "哈密", "喀什", "巴音郭楞", "昌吉", "伊犁", "阿勒泰", "克拉玛依", "博尔塔拉"] }, { name: "香港", cities: ["中西区", "湾仔区", "东区", "南区", "九龙-油尖旺区", "九龙-深水埗区", "九龙-九龙城区", "九龙-黄大仙区", "九龙-观塘区", "新界-北区", "新界-大埔区", "新界-沙田区", "新界-西贡区", "新界-荃湾区", "新界-屯门区", "新界-元朗区", "新界-葵青区", "新界-离岛区"] }, { name: "澳门", cities: ["花地玛堂区", "圣安多尼堂区", "大堂区", "望德堂区", "风顺堂区", "嘉模堂区", "圣方济各堂区", "路氹城"] }]; (function () { document.myReady(function () { // 动态创建省的option initSel(); // 绑定省下拉列表的改变事件 var proSel = document.getElementById("pro"); EventUtil.addEvent(proSel, "change", function (e) { initCity(); }); // 页面加载完成和省的数据加载完成后,初始化城市的选项数据 initCity(); }); // 初始化城市信息 function initCity() { // 当省的改变的时候,加载省城市信息,并把城市创建出option加到城市的select标签中 var cities, // 所有对应选择省的城市名字集合 proSel = document.getElementById("pro"), proName = proSel.value, // 拿到当前选择的省 citySel = document.getElementById("city"); //城市下拉列表 // 根据省的名字,拿到所有对应城市 for (var j = 0; j < data.length; j++) { if (data[j].name == proName) { cities = data[j].cities; // 拿到所有的城市集合 } } // 在输入新的城市之前,先清空之前的城市选项 citySel.innerHTML = ""; // 拿到城市后,把城市的名字创建成option添加到城市的select中去 for (var m = 0; m < cities.length; m++) { var optcity = document.createElement("option"); optcity.value = cities[m]; optcity.text = cities[m]; citySel.add(optcity, null); } } function initSel() { var proSel = document.getElementById("pro"); // 遍历data数组创建省option for (var i = 0; i < data.length; i++) { // <option value="北京">北京</option> var opt = document.createElement("option"); opt.value = data[i].name; opt.text = data[i].name; // option添加到省的下拉列表中去 proSel.add(opt, null); } } })(); </script> </body> </html>
权限选择案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>权限选择</title> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> <style> select { width: 100px; height: 200px; float: left; } .box { width: 100px; float: left; text-align: center; } input { width: 51px; } </style> </head> <body> <select name="l" id="l" multiple="multiple"> <option value="1">添加商品</option> <option value="2">读取商品</option> <option value="3">修改商品</option> <option value="4">删除订单</option> <option value="5">用户查看</option> </select> <div class="box" id="box"> <input type="button" value=">" id="" dir="add"> <input type="button" value=">>" id="" dir="addAll"> <input type="button" value="<" id="" dir="del"> <input type="button" value="<<" id="" dir="delAll"> </div> <select name="r" id="r" multiple="multiple"> </select> <script> (function(){ document.myReady(function(){ // 下面给四个input按钮绑定事件 var box = document.getElementById("box"); EventUtil.addEvent(box,"click",function(e){ // 拿到事件源对象 var target = EventUtil.getTarget(e); if( target === this ){ // 说明点击的是当前的div return; //直接结束当前的点击事件处理程序 } var dir = target.getAttribute("dir"); var l = document.getElementById("l"); var r = document.getElementById("r"); switch(dir) { case "add": add(false,l,r); break; case "addAll": add(true,l,r); break; case "del": add(false,r,l); break; case "delAll": add(true,r,l); break; } }); }); // 接受三个参数,第一个参数是否全部进行移动 // 第二个和第三个参数是要处理的select标签 function add(isAll,sel1,sel2){ // 从sel1的option踢动到sel2的里面去 // 先把所有的需要移动到sel2里面的option都取到array var tempArray = []; // 放要移动的选项的数组 for( var i = 0;i < sel1.options.length; i++ ){ if( isAll || sel1.options[i].selected ){ tempArray.push( sel1.options[i] ); } } // 最后一步 要把要移动的选项放到sel2 while( tempArray.length > 0 ){ var opt = tempArray.pop(); // ie // option的DOM选项对象都有index属性 就是索引 sel1.remove(opt.index); sel2.add(opt,null); } } })(); </script> </body> </html>
全选和全不选案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>全选和全不选</title> <style> html,body,div,table,tr,td,th,thead,tbody { padding: 0; margin: 0; } .tab { border-collapse: collapse; line-height: 25px; border: 1px solid #ccc; text-align: center; } .tab thead { background-color: #aaa; } .tab tbody { background-color:#eee; } .tab tbody tr:nth-child(even) { background-color: #ddd; } .tab td,th { border:1px solid #ccc; padding:5px; } .tab tbody tr:hover { background-color:#fff; } </style> <script src="../js/documentReady.js"></script> <script src="../js/EventUtil.js"></script> </head> <body> <table class="tab" id="tab"> <thead> <tr> <th><input type="checkbox" name="" id="ckAll"></th> <th>用户名</th> <th>性别</th> <th>级别</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox" name="" id=""></td> <td>老马</td> <td>男</td> <td>10</td> </tr> <tr> <td><input type="checkbox" name="" id=""></td> <td>神兽</td> <td>男</td> <td>10</td> </tr> <tr> <td><input type="checkbox" name="" id=""></td> <td>男神</td> <td>女</td> <td>10</td> </tr> <tr> <td><input type="checkbox" name="" id=""></td> <td>梅西</td> <td>男</td> <td>5</td> </tr> </tbody> </table> <script> (function(){ document.myReady(function(){ var ckAll = document.getElementById("ckAll"); EventUtil.addEvent(ckAll,"click",function(e){ // this.checked 通过这个属性可以获得当前多选框是否被选中 var inputArray = document.querySelectorAll("#tab tbody tr td:first-child input"); for( var i = 0 ;i < inputArray.length; i++ ){ inputArray[i].checked = this.checked; } }); }); })(); </script> </body> </html>
许愿墙案例:https://www.bilibili.com/video/av26087098/?p=69
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>许愿墙</title> <style> html, body, div, p { padding: 0; margin: 0; } body { background: red url(../imgs/bg.gif) repeat; font: 12px/20px Arial, "simsun", "Tahoma", "sans-serif"; } .wall { width: 960px; height: 627px; background: red url(../imgs/content_bg.jpg) no-repeat; margin: 0 auto; position: relative; } .tip { width: 227px; position: absolute; cursor: move; } .tip .tip_h { height: 68px; background: url(../imgs/tip1_h.gif) no-repeat; position: relative; } .tip .tip_c { height: 60px; background: url(../imgs/tip1_c.gif) repeat-y; padding: 10px; overflow: hidden; } .tip .tip_f { height: 73px; background: url(../imgs/tip1_f.gif) no-repeat; text-align: right; line-height: 73px; color: blue; padding-right: 20px; font-size: 12px; } .tip .tip_h .head-msg { padding-top: 40px; padding-left: 10px; } .tip .tip_h .closeBtn { position: absolute; top: 20px; right: 20px; cursor: pointer; } </style> </head> <body> <div id="wall" class="wall"> <!-- <div class="tip"> <div class="tip_h"> <div class="head-msg"> 第[4445]条 2016-02-17 00:00:00 </div> <i class="closeBtn"> X </i> </div> <div class="tip_c"> 我学习的是老马视频 我学习的是老马视频 我学习的是老马视频 我学习的是老马视频 </div> <div class="tip_f"> 老马 </div> </div> --> </div> <script> var data = [{ "id": 1, "name": "mahu", "content": "今天你拿苹果支付了么", "time": "2016-02-17 00:00:00" }, { "id": 2, "name": "haha", "content": "今天天气不错,风和日丽的", "time": "2016-02-18 12:40:00" }, { "id": 3, "name": "jjjj", "content": "常要说的事儿是乐生于苦", "time": "2016-03-18 12:40:00" }, { "id": 4, "name": "9.8的妹纸", "content": "把朋友家厕所拉堵了 不敢出去 掏了半小时了都", "time": "2016-03-18 12:40:00" }, { "id": 5, "name": "雷锋ii.", "content": "元宵节快乐", "time": "2016-02-22 12:40:00" }, { "id": 6, "name": "哎呦哥哥.", "content": "据说今晚央视的元宵晚会导演和春晚导演是同一个人,真是躲得过初一,躲不过十五。", "time": "2016-02-22 01:30:00" }, { "id": 7, "name": "没猴哥,不春晚", "content": "班主任:“小明,你都十二岁了,还是三年级,不觉得羞愧吗”?。小明:“一点也不觉得,老师你都四十多岁了,不也是年年在三年级混日子吗?羞愧的应该是你”。老师:……", "time": "2016-02-22 01:30:00" }, { "id": 8, "name": "哎呦杰杰.", "content": "真搞不懂你们地球人,月亮有什么好看的,全是坑,还是对面那哥们好看,", "time": "2016-02-22 01:30:00" }, { "id": 9, "name": "哎呦哎呦", "content": "今天哪里的烟花最好看!!?答:朋友圈。。。", "time": "2016-02-22 02:30:00" } ]; (function () { var maxIndex = 1; var tipArray = []; // 存放所有的tip var isMove = false; // 记录tip是否进行移动 var tempX = 0; var tempY = 0; //鼠标一开始点击的位置 x y var moveNode = null; window.onload = function () { // 页面加载完成后,加载 数据生成tip div并添加到wall loadTipDivs(data); // 给所有的tip绑定mousedown事件,当点击的时候zIndex最大 for (var i = 0; i < tipArray.length; i++) { tipArray[i].onmousedown = function (e) { maxIndex += 1; this.style.zIndex = maxIndex; isMove = true; e = e || window.event; // 记录鼠标点击的位置,以及要进行设置移动的标志位 tempX = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft); tempY = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop); moveNode = this; // 把当前的移动的div设置成鼠标按下的对应的tip标签 }; tipArray[i].onmouseup = function (e) { isMove = false; }; // 实现鼠标移动 tip跟着鼠标移动的代码 tipArray[i].onmousemove = function (e) { e = e || window.event; var pageX = e.clientX + ( document.documentElement.scrollLeft || document.body.scrollLeft ); var pageY = e.clientY + ( document.documentElement.scrollTop || document.body.scrollTop ); var w = pageX - tempX; var h = pageY - tempY; if( isMove && moveNode == this){ this.style.left = parseFloat(this.style.left) + w + "px"; this.style.top = parseFloat(this.style.top) + h + "px"; } tempX = pageX; tempY = pageY; }; } //给所有的额tip的关闭按钮绑定点击事件 var closeBtns = document.getElementsByTagName("i"); for (var j = 0; j < closeBtns.length; j++) { closeBtns[j].onclick = function (e) { this.parentNode.parentNode.style.display = "none"; }; } // }; // 接受一个数组,创建tip的div function loadTipDivs(data) { var strHTMLArray = []; for (var i = 0; i < data.length; i++) { // 拿到 每个 许愿的数据 var itemData = data[i]; var strHTML = ""; strHTML += '<div class="tip">'; strHTML += '<div class="tip_h">'; strHTML += '<div class="head-msg">'; strHTML += '第[' + itemData.id + ']条' + ' ' + itemData.time; strHTML += '</div>';// strHTML += '<i class="closeBtn">';// strHTML += 'X';// strHTML += '</i>';// strHTML += '</div>';// strHTML += '<div class="tip_c">';// strHTML += itemData.content;// strHTML += '</div>';// strHTML += '<div class="tip_f">';// strHTML += itemData.name;// strHTML += ' </div>'; strHTML += '</div>'; strHTMLArray.push(strHTML); } // 把所有的许愿div放到wall里面去 document.getElementById("wall").innerHTML += strHTMLArray.join(""); // 遍历wall里面所有的tip节点,设置一个随机left和top值 for (var i = 0; i < wall.childNodes.length; i++) { if (wall.childNodes[i].nodeType == 1) { wall.childNodes[i].style.left = Math.random() * (960 - 227) + "px"; wall.childNodes[i].style.top = Math.random() * (627 - 221) + "px"; wall.childNodes[i].style.zIndex = 1; //默认所有的zIndex为1 tipArray.push(wall.childNodes[i]); } } } })(); </script> </body> </html>
tab切换案例:https://www.bilibili.com/video/av26087098/?p=73
tab示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>table页签</title> <style> html,body,div,ul,li { padding:0; margin: 0; } ul,ol { list-style: none; } .tab { width: 500px; } body { padding: 100px; } /* 设置tab头部样式 */ .tab .tab-h { height: 30px; position: relative; z-index: 2; /* width: 500px; */ /* border:1px solid magenta; */ } .tab .tab-h .tab-h-item { float: left; border:1px solid #ccc; background-color:#eee; } .tab .tab-h .tab-h-item a{ color:#333; text-decoration: none; width: 100px; float: left; line-height: 28px; text-align: center; } .tab .tab-h li.active{ border-bottom-color: #fff; background-color:#fff; } /* 设置主体 */ .tab .tab-b { border:1px solid #ccc; position: relative; z-index: 1; top:-1px; } .tab .tab-b .tab-b-item { display: none; height: 300px; padding:10px; } .tab .tab-b div.active{ display:block; } </style> </head> <body> <div class="tab"> <!-- tab的头部 --> <div class="tab-h"> <ul class="tab-h-list" id="tabHeadList"> <li class="tab-h-item active" tabid="1"><a href="javascript:void(0)">产品</a></li> <li class="tab-h-item" tabid="2"><a href="javascript:void(0)">用户</a></li> <li class="tab-h-item" tabid="3"><a href="javascript:void(0)">体育</a></li> <li class="tab-h-item" tabid="4"><a href="javascript:void(0)">新闻</a></li> </ul> </div> <!-- tab的主体 --> <div class="tab-b" id="tabBody"> <div class="tab-b-item active" tabid="1">页签1</div> <div class="tab-b-item" tabid="2">页签2</div> <div class="tab-b-item" tabid="3">页签3</div> <div class="tab-b-item" tabid="4">页签4</div> </div> </div> <script> (function(){ window.onload = function(){ var tabHeadList = document.getElementById("tabHeadList"); var liMenu = tabHeadList.getElementsByTagName("li"); for( var i=0;i < liMenu.length;i++ ){ liMenu[i].onclick = function(e){ // 第一 获得点击的tabid tabId = this.getAttribute("tabid"); // 第一: 把自己的样式设置类设置active 其他的li取消active for(var j = 0;j < liMenu.length; j++){ liMenu[j].className = "tab-h-item"; } this.className = "tab-h-item active"; // 第二:所有的tab-b中的div中tabid等于tabId的样式加上active,其他的去掉active var tabBody = document.getElementById("tabBody"); for( var k = 0;k < tabBody.childNodes.length;k++ ){ var item = tabBody.childNodes[k]; if(item.nodeType == 1){//拿到标签节点 if( item.getAttribute("tabid") == tabId ){ item.className = "tab-b-item active"; }else{ item.className = "tab-b-item"; } } } }; }; }; })(); </script> </body> </html>
document总结
文档写入示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文档写入</title> </head> <body> <h1>我是h1标签</h1> <script> // 文档加载过程中,写入文档,会随着页面一块输出 document.write("<h2>我是h2</h2>"); </script> <h3>我是h3标签</h3> <script> (function(){ window.onload = function(){ // 文档加载完成之后再写入,会把之前的覆盖掉 document.open(); document.write("<h1>你好</h1>"); document.close(); } })(); </script> </body> </html>
1.12 BOM详解
window对象描述
BOM + DOM完整结构图
window的open方法
screen对象
1.13 DOM特效封装
模态对话框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>E64-模态对话框.html</title> <style> html,body,div,input { margin: 0; padding: 0; } .dialog-wrap { display:none; } .dialog{ border:1px solid #ccc; width: 300px; /* display: none; */ position: absolute; background-color:#eee; top:50%; left:50%; margin-left:-151px; margin-top:-151px; z-index: 1000; } .dialog-h { border-bottom: 1px solid #ccc; height: 30px; position: relative; } .dialog-h .btn-close { position: absolute; right:15px; top:0px; cursor: pointer; } .dialog-b { height: 267px; } .dialog-cover{ /* 如果是一个div,父容器是body,而且是绝对定位,那么left bottom right top都设置为0 则会铺满整个屏幕 */ position: absolute; top:0; bottom:0; right:0; left:0; background-color: #ddd; z-index:100; /* 设置透明 */ filter:alpha(opacity=50); opacity:0.5; } </style> </head> <body> <input type="button" value="弹出对话框" id="btn"> <div class="dialog-wrap" id="dialogBox"> <div class="dialog-cover"></div> <div class="dialog" id="dialog"> <div class="dialog-h"> <h3>对话框的头部</h3> <i class="btn-close" id="btnClose">X</i> </div> <div class="dialog-b"> 对话框的内容 </div> </div> </div> <script> (function(){ window.onload = function(){ var btn = document.getElementById("btn"); btn.onclick = function(){ var divDialog = document.getElementById("dialogBox"); divDialog.style.display = "block"; }; var btnClose = document.getElementById("btnClose"); btnClose.onclick = function(){ this.parentNode.parentNode.parentNode.style.display = "none"; }; }; })(); </script> </body> </html>
模态对话框封装
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>E64-模态对话框.html</title> <style> html,body,div,input { margin: 0; padding: 0; } .dialog-wrap { display:none; } .dialog{ border:1px solid #ccc; width: 300px; /* display: none; */ position: absolute; background-color:#eee; top:50%; left:50%; margin-left:-151px; margin-top:-151px; z-index: 1000; } .dialog-h { border-bottom: 1px solid #ccc; height: 30px; position: relative; } .dialog-h .btn-close { position: absolute; right:15px; top:0px; cursor: pointer; } .dialog-b { height: 267px; } .dialog-cover{ /* 如果是一个div,父容器是body,而且是绝对定位,那么left bottom right top都设置为0 则会铺满整个屏幕 */ position: absolute; top:0; bottom:0; right:0; left:0; background-color: #ddd; z-index:100; /* 设置透明 */ filter:alpha(opacity=50); opacity:0.5; } </style> <script src="../js/L.js"></script> </head> <body> <input type="button" value="弹出对话框" id="btn"> <div class="dialog-wrap" id="mDialog" title="弹出来的对话框"> <!-- 规定:用户要使用dialog对话框,必须 1、div的class dialog-wrap 2、须要给div增加title属性,如果没有增加,那么标题是空的 3、div的innerHTML就是现在在对话框上的信息 --> 在对话框里面显示的内容 <p>老马是好样的!</p> <input type="button" value="关闭" id=""> </div> <script> (function(){ window.onload = function(){ var btn = document.getElementById("btn"); btn.onclick = function(){ // 在#mDialog上进行创建一个模态对话框 // var dialog = new Dialog("#mDialog"); var dialog = L.Dialog("#mDialog"); //如果用户没有用new 也不会报错 // 可能框架有多个组件 要兼容扩展其他的组件 L框架 dialog.show(); // 对话框弹出 }; }; })(); </script> </body> </html>
slidedown
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>slidedown</title> <style> html,body,div { margin: 0; padding: 0; } .wrap { margin:0 auto; width: 960px; } .box { border:1px solid red; width: 300px; height: 300px; background-color: #eee; } </style> </head> <body> <div class="wrap"> <input type="button" value="折叠" id="btnSlideUp"> <input type="button" value="展开" id="btnSlideDown"> <div class="box" id="box"> 我是box </div> </div> <script> (function(){ window.onload = function(){ var btnSlideUp = document.getElementById("btnSlideUp"), btnSlideDown = document.getElementById("btnSlideDown"), box = document.getElementById("box"); // 点击折叠按钮后,让div一点一点进行折叠 btnSlideUp.onclick = function(e){ var start = Date.now(); //返回当前时间的utc 1970毫秒数 // 随着时间推移,让div的高度一致减小,最后为0 display:none var originH = box.clientHeight; //拿到显示的高度 div height // 1秒钟后 div消失 1000ms var timer = setInterval(function(){ // var now = Date.now(); // console.log( now - start ); //连个时间相差的毫秒数 // start = now; // 思路一 当前时间和上一次执行的相隔时间执行div减少高度操作 // 思路二 当前时间跟最易开始的事件进行计算,把相差总时间换算成应该减少的高度 // 应该减少的高度,然后设置div的高度 var now = Date.now(); var nowH = originH - originH * ( now - start ) / 1000 box.style.height = nowH + "px"; if(nowH <= 0){ // 停止折叠,并且把当前div隐藏,并且把时钟去掉 box.style.display = "none"; box.style.height = originH +"px"; //隐藏后,还要把它恢复到原来的状态 clearInterval(timer); } },1000/60); }; btnSlideDown.onclick = function(e){ var start = Date.now(); // 最开始的时间 // 如果div的display为none 那么 clientHeight 为0 box.style.display = "block"; var originH = box.clientHeight; box.style.height = "0px"; var timer = setInterval(function(){ var now = new Date(); box.style.height = originH * ( now - start )/ 1000 + "px"; if( originH * ( now - start )/ 1000 >= originH ){ box.style.height = originH + "px"; clearInterval(timer); } },1000/60); }; }; })(); </script> </body> </html>
使用组件进行动画
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>使用组件进行动画</title> <style> .box { height: 400px; width: 300px; border: 1px solid #ccc; display: none; background-color: #eee; } </style> <script src="../js/L.js"></script> </head> <body> <input type="button" value="向下滚动" id=btn> <div class="box" id="box"> </div> <script> (function(){ window.onload = function(){ var btn = document.getElementById("btn"); var box = document.getElementById("box"); btn.onclick = function(e){ L.slideDown( box,400 ); }; }; })(); </script> </body> </html>
轮播图
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>轮播图</title> <style> html,body,div,ul,li { padding: 0; margin: 0; } ul,ol { list-style: none; } a { text-decoration: none; color: #000; } .slideshow { width: 500px; height: 300px; border:1px solid #ccc; margin: 100px auto; overflow: hidden; position: relative; } .slideshow .slide-img-wrap{ width: 2000px; position: absolute; z-index: 1; } .slideshow .slide-img-wrap li { float: left; width: 500px; } .slideshow .slide-img-wrap li img{ width: 500px; } .slideshow .slide-btn-wrap { position: absolute; z-index: 100; top:50%; left: 0; height: 30px; width: 500px; } .slideshow .slide-btn-wrap a { color:#999; width: 30px; height: 30px; font-size: 30px; line-height: 30px; text-align: center; font-weight: bold; background-color: rgba(99,99,99,0.5); margin:5px; } .slideshow .slide-btn-wrap a:hover { background-color: rgba(99,99,99,0.8); } .slideshow .slide-btn-wrap .next { float:right; } .slideshow .slide-btn-wrap .prev { float:left; } .slideshow .slide-sel-btn { position: absolute; top:80%; height: 10px; width: 64px; z-index: 100; left: 50%; margin-left: -28px; } .slideshow .slide-sel-btn a { border-radius: 50%; background-color: #fff; width: 8px; height: 8px; margin-right: 8px; float: left; } .slideshow .slide-sel-btn a.on { background-color: #999; } </style> </head> <body> <div class="slideshow"> <!-- 滚动的图片 --> <ul class="slide-img-wrap"> <li index="0" class="on"><a href="#" ><img src="../imgs/1.jpg" alt=""></a></li> <li index="1"><a href="#"><img src="../imgs/2.jpg" alt=""></a></li> <li index="2"><a href="#"><img src="../imgs/3.jpg" alt=""></a></li> <li index="3"><a href="#"><img src="../imgs/4.jpg" alt=""></a></li> </ul> <!-- 上一张和下一张的按钮 --> <div class="slide-btn-wrap"> <a href="#" class="prev"><</a> <a href="#" class="next">></a> </div> <div class="slide-sel-btn"> <a index="0" href="#" class="on"></a> <a index="1" href="#"></a> <a index="2" href="#"></a> <a index="3" href="#"></a> </div> </div> <script> (function(){ window.onload = function(){ var btnNext = document.querySelector(".slide-btn-wrap .next"); btnNext.onclick = function(e){ // 滑动到 下一张 图片 var curLi = document.querySelector(".slide-img-wrap .on"); var curIndex = curLi.getAttribute("index"); curIndex = parseInt( curIndex ); console.log(curIndex); // 让索引进行循环 var nextIndex = (curIndex + 1) % 4; var nextLeft = nextIndex * (-500); // 要让下一个图片的左侧 放到盒子的最左侧 var imgList = document.querySelector(".slide-img-wrap"); // imgList.style.left = (imgList.offsetLeft - 500 ) + "px"; imgList.style.left = nextLeft + "px"; // 把li标签和a标签中的class 中的on设置一下 var liArray = document.querySelectorAll(".slide-img-wrap li"); liArray[curIndex].className = "n"; liArray[nextIndex].className = "on"; var slideSelBtnArray = document.querySelectorAll(".slide-sel-btn a"); slideSelBtnArray[curIndex].className = ""; slideSelBtnArray[nextIndex].className = "on"; autoSlide(); }; var btnPrev = document.querySelector(".slide-btn-wrap .prev"); btnPrev.onclick = function(e){ // 滑动到 上一张 图片 var curLi = document.querySelector(".slide-img-wrap .on"); var curIndex = curLi.getAttribute("index"); curIndex = parseInt( curIndex ); console.log(curIndex); // 让索引进行循环 var prevIndex = (curIndex - 1 + 4) % 4; var prevLeft = prevIndex * (-500); // 要让下一个图片的左侧 放到盒子的最左侧 var imgList = document.querySelector(".slide-img-wrap"); // imgList.style.left = (imgList.offsetLeft - 500 ) + "px"; imgList.style.left = prevLeft + "px"; // 把li标签和a标签中的class 中的on设置一下 var liArray = document.querySelectorAll(".slide-img-wrap li"); liArray[curIndex].className = "n"; liArray[prevIndex].className = "on"; var slideSelBtnArray = document.querySelectorAll(".slide-sel-btn a"); slideSelBtnArray[curIndex].className = ""; slideSelBtnArray[prevIndex].className = "on"; autoSlide(); }; // 具体选中圆圈的跳转页面 var selBtnDiv = document.querySelector(".slide-sel-btn"); selBtnDiv.onclick = function(e){ e = e || window.event; var target = e.target || e.srcElement; if(target == this){ return; } // 如果是点击了元素a标签 var nextIndex = target.getAttribute("index"); nextIndex = parseInt( nextIndex ); // 设置为on的样式类的a标签 var curA = document.querySelector( ".slide-sel-btn .on" ); var curIndex = curA.getAttribute( "index" ); curIndex = parseInt( curIndex ); slide( curIndex,nextIndex ); autoSlide(); }; // 自动轮播 autoSlide(); var timer; // 实现自动轮播的方法 function autoSlide(){ //先去掉时钟 if(timer){ clearInterval(timer); timer = null; } timer = setInterval( function(){ slideShowNext(); },2000 ); } function slideShowNext(){ // 滑动到 下一张 图片 var curLi = document.querySelector(".slide-img-wrap .on"); var curIndex = curLi.getAttribute("index"); curIndex = parseInt( curIndex ); console.log(curIndex); // 让索引进行循环 var nextIndex = (curIndex + 1) % 4; slide( curIndex,nextIndex ); } function slide( curIndex,nextIndex ){ var imgList = document.querySelector(".slide-img-wrap"); var nextLeft = nextIndex * (-500); var curLeft = imgList.offsetLeft; // 动画轮播 slideAnimate( curLeft,nextLeft,imgList,300 ); // 要让下一个图片的左侧 放到盒子的最左侧 // imgList.style.left = (imgList.offsetLeft - 500 ) + "px"; // imgList.style.left = nextLeft + "px"; // 把li标签和a标签中的class 中的on设置一下 var liArray = document.querySelectorAll(".slide-img-wrap li"); liArray[curIndex].className = "n"; liArray[nextIndex].className = "on"; var slideSelBtnArray = document.querySelectorAll(".slide-sel-btn a"); slideSelBtnArray[curIndex].className = ""; slideSelBtnArray[nextIndex].className = "on"; } // 对元素进行连续的滚动 function slideAnimate( curLeft,endLeft,element,duration ){ var w = endLeft - curLeft; var wPerMS = w / duration; var startTime = Date.now(); var animateTimer = setInterval( function(){ var curTime = Date.now(); // 每一帧直接的事件间隔 var delateTime = curTime - startTime; element.style.left = (element.offsetLeft + delateTime * wPerMS) + "px"; duration = duration - delateTime; if( duration <= 0 ){ element.style.left = endLeft + "px"; clearInterval( animateTimer ); return; } startTime = curTime; },1000/60 ); } }; })(); </script> </body> </html>
手风琴
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>手风琴 效果 </title> <style> html,body,ul,li,div { margin: 0; padding: 0; } ul,li { list-style: none; } .ac { width: 300px; margin: 100px auto; border:1px solid red; } .ac .ac-item .ac-item-hd { height: 30px; line-height: 30px; background-color: #efefef; border:1px solid #ddd; cursor: pointer; } .ac .ac-item .ac-item-bd { height: 150px; display: none; } .ac .ac-item.on .ac-item-bd{ display: block; } </style> </head> <body> <ul class="ac" id="ac"> <li class="ac-item on"> <div class="ac-item-hd">头部1</div> <div class="ac-item-bd">内容1</div> </li> <li class="ac-item"> <div class="ac-item-hd">头部2</div> <div class="ac-item-bd">内容2</div> </li> <li class="ac-item"> <div class="ac-item-hd">头部3</div> <div class="ac-item-bd">内容3</div> </li> <li class="ac-item"> <div class="ac-item-hd">头部4</div> <div class="ac-item-bd">内容4</div> </li> </ul> <script> (function(){ window.onload = function(){ var ac = document.getElementById("ac"); var liList = ac.getElementsByTagName("li"); for( var i=0; i < liList.length;i++ ){ liList[i].onclick = function(e){ // 先将所有的li标签设置为ac-item for( var j=0;j < liList.length;j++ ){ liList[j].className = "ac-item"; } // 再将点击的li标签设置为 ac-item on this.className = "ac-item on"; }; } }; })(); </script> </body> </html>
表单校验
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>表单校验</title> </head> <body> <form action="#" id="frm"> <table> <tr> <td>示例email</td> <td> <input type="email" name="" id=""> <input type="number" name="" id=""> <input type="date" name="" id=""> </td> </tr> <tr> <td>姓名:</td> <td><input type="text" name="txtName" placeholder="文本不少于6个字符" id="txtName"></td> </tr> <tr> <td>邮箱:</td> <td><input type="text" name="txtEmail" id="txtEmail"></td> </tr> <tr> <td>Tel:</td> <td><input type="text" name="txtTel" id="txtTel"></td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交" id=""> <input type="reset" name="重置" id=""> </td> </tr> </table> </form> <table> </table> <script> (function(){ window.onload = function(){ // 拿到表单 var frm = document.getElementById("frm"); // 表单提交的时候先执行此事件响应方法 frm.onsubmit = function(e){ // 校验用户性文本框的字符不少于6个字符 var txtName = document.getElementById("txtName"); // 用户名长度错误是提示的消息 var txtNameMsg = document.createElement("span"); txtNameMsg.innerHTML = "姓名的字符串长度必须在6-20之间"; txtNameMsg.style.color = "red"; var txtNameRepExp = /\w{6,20}/gi; if( txtNameRepExp.test(txtName.value) ){ // 移除错误的文本框消息 txtName.parentNode.removeChild(txtNameMsg); }else{ // 校验失败,添加错误信息 取消默认操作 txtName.parentNode.appendChild(txtNameMsg); return false; } e = e ||window.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue = false; } return false; }; }; })(); </script> </body> </html>
未完待续