web 前端3 DOM
文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口。它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。我们最为关心的是,DOM把网页和脚本以及其他的编程语言联系了起来。DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容
一、查找元素
1、直接查找
document.getElementById 根据ID获取一个标签 document.getElementsByName 根据name属性获取标签集合 document.getElementsByClassName 根据class属性获取标签集合 document.getElementsByTagName 根据标签名获取标签集合
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DOM</title> </head> <body> <div> 123 <div class="c1">asdf</div> <div class="c1" id="i1"> <p>asdf</p> <div name="n1"> <span>asd</span> </div> <div name="n1"> <a>dfs</a> <a>asdf</a> </div> </div> <div class="c1">asdf</div> </div> <script> var i1= document.getElementById("i1") // 单个元素 var class_names = document.getElementsByClassName("c1") //集合元素 for循环 var tag_names = document.getElementsByTagName("a") //集合元素 for循环 var names = document.getElementsByName("n1") //集合元素 for循环 console.log(i1) for (i in class_names){ console.log(class_names[i]) }; for (i in tag_names){ console.log(tag_names[i].innerText) }; for (i in names){ console.log(names[i].innerText) } </script> </body> </html>
2间接查找
parentNode // 父节点 childNodes // 所有子节点 firstChild // 第一个子节点 lastChild // 最后一个子节点 nextSibling // 下一个兄弟节点 previousSibling // 上一个兄弟节点 parentElement // 父节点标签元素 children // 所有子标签 firstElementChild // 第一个子标签元素 lastElementChild // 最后一个子标签元素 nextElementtSibling // 下一个兄弟标签元素 previousElementSibling // 上一个兄弟标签元素
<div> 123 <div class="c1">asdf</div> <div class="c1" id="i1"> <p>asdf</p> <div name="n1"> <span>asd</span> </div> <div name="n1"> <a>dfs</a> <a>asdf</a> </div> </div> <div class="c1">asdf</div> </div> <script> var i1= document.getElementById("i1") // 单个元素 father_ele = i1.parentElement //获取到父标签的html // father_ele = i1.parentNode //获取到父标签的html 只有childnode 没有children // console.log(father_ele) // sons = father_ele.childNodes sons = father_ele.childNodes //parentElement 和 parentNode 都有。含文本123 sons = father_ele.children //parentElement 的方法,不含文本123 for (i in sons){ console.log(sons[i]) } </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="c1" name="alex" tag="sd2"> 11 <a class="a1">1</a> <a class="a2">2</a> <a class="a1">3</a> </div> <div class="c2"> 22</div> <div class="c3">33</div> <div class="c4">44</div> </body> <script type="text/javascript"> var first_chile = document.getElementsByClassName("c1")[0] console.log(first_chile.firstChild) //11 第一个子node 算上文本的第一个 console.log(first_chile.firstChild.nextSibling) // <a class="a1">1</a> 下一个子node console.log(first_chile.firstChild.nextSibling.previousSibling) //11 上一个子node console.log(first_chile.lastChild.previousSibling) //最后一个子node 问题为什么最后一个子node 是text console.log(first_chile.lastChild) //最后一个子node 问题为什么最后一个子node 是text </script> <script> var x = document.getElementsByClassName("a1")[0] console.log(x.parentElement) //拿到父节点div整个内容 console.log(x.parentElement.children) //列表拿到子节点们 console.log(x.parentElement.firstElementChild) //<a class="a1">1</a> 不算上文本的第一个 console.log(x.parentElement.lastElementChild) //<a class="a3">3</a> 不算上文本的第一个 console.log(x.parentElement.firstElementChild.nextElementSibling) //<a class="a2">2</a> console.log(x.parentElement.firstElementChild.nextElementSibling.previousElementSibling) //<a class="a1">1</a> </script> </html>
二、操作
1、内容
innerText 文本 outerText innerHTML HTML内容 innerHTML value 值
内容处理 innerText innerHtml value 根据内容的value取值 input text password textare 都可以value 特殊value checkbox value checked = true radio value checked = true select selected = selected 要结合value,value的值是谁,selected就是谁 value 更改默认选项 selectIndex 可以更改默认选项
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>全选反选 取消</title> </head> <body> <table> <div> <input type="button" value="全选" ondblclick="f1();"> <input type="button" value="取消" onclick="f1();"> <!--<input type="button" value="取消" onclick="f2();">--> <input type="button" value="反选" onclick="f3();"> </div> <thead style="border: 1px solid gray;"> <tr> <td>序号</td> <td> 用户名</td> <td> 年龄</td> </tr> </thead> <tbody id="tb"> <tr> <td><input class="c1" type="checkbox"></td> <td>alex</td> <td>19</td> </tr> <tr> <td><input class="c1" type="checkbox"></td> <td>alex</td> <td>19</td> </tr> <tr> <td><input class="c1" type="checkbox"></td> <td>alex</td> <td>19</td> </tr> <tr> <td><input class="c1" type="checkbox"></td> <td>alex</td> <td>19</td> </tr> </tbody> </table> <script type="text/javascript"> // 第二种 function f1() { var class_inpu = document.getElementById("tb"); var checks = class_inpu.getElementsByClassName("c1") for (var i=0;i<checks.length;i++){ if (checks[i].classList.length >1){ checks[i].checked = false; checks[i].className = "c1" } else if(checks[i].classList.length == 1){ checks[i].checked = true; checks[i].className = "c1 c2" } }; } function f3() { var class_inpu = document.getElementById("tb"); var checks = class_inpu.getElementsByClassName("c1") for (var i = 0; i < checks.length; i++) { if (checks[i].checked){ checks[i].checked = false; }else{ checks[i].checked = true; } }; } // 第二种 // function f1() { // var class_inpu = document.getElementById("tb"); // var checks = class_inpu.getElementsByClassName("c1") // for (var i=0;i<checks.length;i++){ // checks[i].checked = true; // }; // } // function f2() { // var class_inpu = document.getElementById("tb"); // var checks = class_inpu.getElementsByClassName("c1") // for (var i=0;i<checks.length;i++){ // checks[i].checked = false ; // }; // } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="i1"> <ul> <li><input type="checkbox" value="1"> 篮球</li> <li><input type="checkbox" value="2"> z球</li> <li><input type="checkbox" value="3"> p球</li> </ul> </div> <div id="i2"> <ul> <li><input type="checkbox" value="11"> 篮球</li> <li><input type="checkbox" value="22"> z球</li> <li><input type="checkbox" value="33"> p球</li> </ul> </div> <input type="button" value="全部选中 i1" onclick="Clic()"> <input type="button" value="全部取消 i1" onclick="Clic2()"> <script type="text/javascript"> var tag_name = document.getElementById("i1").getElementsByTagName("input") function Clic() { for (i in tag_name){ tag_name[i].checked = true }; }; function Clic2() { for ( i in tag_name){ tag_name[i].checked = false }; }; </script> </body> </html> <!-- 内容处理 innerText innerHtml value 根据内容的value取值 input text password textare 都可以value 特殊value checkbox value checked = true radio value checked = true select selected = selected 要结合value,value的值是谁,selected就是谁 value 更改默认选项 selectIndex 可以更改默认选项 -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>select</title> </head> <body> <select id="x" name="xx"> <option value="11">北京</option> <option value="12" selected="selected">上海</option> <option value="13">广州</option> <option value="14">河北</option> </select> <!-- 更改选择第一种 value控制 a = document.getElementById("x") <select id="x" name="xx">…</select> a <select id="x" name="xx">…</select> a.value "12" a.value=13 13 a.value=14 14 更改选则的第二种 a = document.getElementById("x") <select id="x" name="xx">…</select> a <select id="x" name="xx">…</select> a.selectedIndex 1 a.selectedIndex=2 2 --> <!-- select selected = selected 要结合value,value的值是谁,selected就是谁 value 更改默认选项 selectIndex 可以更改默认选项 --> </body> </html>
select selected = selected 要结合value,value的值是谁,selected就是谁 value 更改默认选项 selectIndex 可以更改默认选项
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li><input type="radio" name="g" value="11"/>男</li> <li><input type="radio" name="g" value="22"/>女</li> <li><input type="radio" name="g" value="33"/>中</li> </ul> <script> var radios = document.getElementsByTagName('input'); // radios[1].value //radios //[<input type="radio" name="g" value="11">, <input type="radio" name="g" value="22">, <input type="radio" name="g" value="33">] //radios[0] //<input type="radio" name="g" value="11"> //radios[0].checked //false //radios[0].checked = true //true </script> </body> </html>
2、属性
attributes // 获取所有标签属性 setAttribute(key,value) // 设置标签属性 getAttribute(key) // 获取指定标签属性 /* var atr = document.createAttribute("class"); atr.nodeValue="democlass"; document.getElementById('n1').setAttributeNode(atr); */
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <input type="button" value="全选" onclick="CheckAll();"/> <input type="button" value="取消" onclick="CancelAll();"/> <input type="button" value="反选" onclick="ReverseCheck();"/> <table border="1" > <thead> </thead> <tbody id="tb"> <tr> <td><input type="checkbox" /></td> <td>111</td> <td>222</td> </tr> <tr> <td><input type="checkbox" /></td> <td>111</td> <td>222</td> </tr> <tr> <td><input type="checkbox" /></td> <td>111</td> <td>222</td> </tr> <tr> <td><input type="checkbox" /></td> <td>111</td> <td>222</td> </tr> </tbody> </table> <script> function CheckAll(ths){ var tb = document.getElementById('tb'); var trs = tb.childNodes; for(var i =0; i<trs.length; i++){ var current_tr = trs[i]; if(current_tr.nodeType==1){ var inp = current_tr.firstElementChild.getElementsByTagName('input')[0]; inp.checked = true; } } } function CancelAll(ths){ var tb = document.getElementById('tb'); var trs = tb.childNodes; for(var i =0; i<trs.length; i++){ var current_tr = trs[i]; if(current_tr.nodeType==1){ var inp = current_tr.firstElementChild.getElementsByTagName('input')[0]; inp.checked = false; } } } function ReverseCheck(ths){ var tb = document.getElementById('tb'); var trs = tb.childNodes; for(var i =0; i<trs.length; i++){ var current_tr = trs[i]; if(current_tr.nodeType==1){ var inp = current_tr.firstElementChild.getElementsByTagName('input')[0]; if(inp.checked){ inp.checked = false; }else{ inp.checked = true; } } } } </script> </body> </html> Demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>修改属性</title> </head> <body> <div> <input type="button" onclick="Func();" value="点我修改123"> </div> <div id="x"> <div class="c1" alex="sb">123</div> <div class="c1">123</div> <div class="c1" alex="sb">123</div> <div class="c1" alex="sb">123</div> <div class="c1" >123</div> <div class="c1" >123</div> <div class="c1" alex="sb">123</div> </div> <script type="text/javascript"> function Func() { var check = document.getElementById("x").children for (var i=0;i<check.length;i++){ if (check[i].getAttribute("alex") == "sb"){ check[i].innerText = "456" } } } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>导航内容切换</title> <style> ul{ list-style: none; padding: 0; margin: 0; } ul li{ float: left; /*background-color: #e8e8e8;*/ color: #1a1c24; padding: 8px 10px; border: 0.3px solid black; border-radius: 4px; margin-right: 4px; } .clear_fix:after{ display: block; content: '.'; height: 0; visibility: hidden; clear: both; } .hide{ display: none; } .tab-menu .title{ background-color: #dddddd; } .tab-menu .title .active{ background-color: white; color: black; border: 0.3px solid red; border-radius: 4px; } .tab-menu .content{ border: 1px solid #dddddd; min-height: 150px; } </style> </head> <body> <div style="min-width: 1000px;width: 80%;margin: 0 auto;"> <div class="tab-menu"> <div class="title clear_fix"> <ul> <li target="h1" class="active" onclick="Show(this);">价格趋势</li> <li target="h2" onclick="Show(this);">市场分布</li> <li target="h3" onclick="Show(this);">其他</li> </ul> </div> <div id="content" class="content"> <div con="h1">content1</div> <div con="h3" class="hide">content2</div> <div con="h2" class="hide">content3</div> </div> </div> </div> <script type="text/javascript"> function Show(obj) { var fa_con = obj.getAttribute("target") var sons = obj.parentElement.children; for (var i=0;i<sons.length;i++){ // sons[i].className = "" if (obj != sons[i]){ sons[i].className = "" // sons[i].removeAttribute("class") }else { obj.className = "active" } }; // obj.className = 'active' var conte = document.getElementById("content").children; for (var j=0;j<conte.length;j++){ var val_con = conte[j].getAttribute("con") if (val_con == fa_con){ conte[j].classList.remove("hide") }else { conte[j].className = "hide" } } } </script> </body> </html>
3、class操作 以上案例用到了
className // 获取所有类名 classList.remove(cls) // 删除指定类 classList.add(cls) // 添加类
4、标签操作
a.创建标签
// 方式一 创建的方式 var tag = document.createElement('a') tag.innerText = "wupeiqi" tag.className = "c1" tag.href = "http://www.cnblogs.com/wupeiqi" // 方式二 字符串拼接 var tag = "<a class='c1' href='http://www.cnblogs.com/wupeiqi'>wupeiqi</a>"
b.操作标签
// 方式一 insertAdjacentHTML var obj = "<input type='text' />"; xxx.insertAdjacentHTML("beforeEnd",obj); xxx.insertAdjacentElement('afterBegin',document.createElement('p')) //注意:第一个参数只能是'beforeBegin'、 'afterBegin'、 'beforeEnd'、 'afterEnd' // 方式二 标签添加子标签 创建<p>添加<a> var tag = document.createElement('a') xxx.appendChild(tag) // 为xxx标签添加子标签 xxx.insertBefore(tag,xxx[1])
1 字符串拼接
var str = "<li>" + val + "</li>" new_this.insertAdjacentHTML("beforeEnd",str);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>操作标签增加内容</title> </head> <body> <div> <input type="text"> <input type="button" value="添加一条" onclick="Inert(this);"> </div> <div> <ul id="ul_new"> <li>alex</li> <li>eric</li> </ul> </div> <script type="text/javascript"> function Inert(obj) { var val = obj.previousElementSibling.value; obj.previousElementSibling.value = " "; var new_this = document.getElementById("ul_new"); var str = "<li>" + val + "</li>" new_this.insertAdjacentHTML("beforeEnd",str); } </script> </body> </html>
2 创建标签添加
// 第二种方式 元素 节点的方式 var tag = document.createElement("li") tag.innerText = val; var temp = document.createElement("a") tag.innerText = "百度"; temp.href = "http://www.baidu.com" tag.appendChild(temp) commentList.insertBefore(tag,commentList.children[1])
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>操作标签增加内容</title> </head> <body> <div> <input type="text"> <input type="button" value="添加一条" onclick="Inert(this);"> </div> <div> <ul id="commentList"> <li>alex</li> <li>eric</li> </ul> </div> <script type="text/javascript"> function Inert(obj) { var val = obj.previousElementSibling.value; console.log(val) obj.previousElementSibling.value = " "; var commentList = document.getElementById("commentList"); // 第二种方式 元素 节点的方式 var tag = document.createElement("li") tag.innerText = val; var temp = document.createElement("a") tag.innerText = "百度"; temp.href = "http://www.baidu.com" tag.appendChild(temp) commentList.insertBefore(tag,commentList.children[1]) } </script> </body> </html>
3 在制定的 标签前后添加 新的标签或者文本
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <div> <input type="text" /> <input type="button" value="添加" onclick="AddElement(this);" /> </div> <div style="position: relative;"> <ul id="commentList"> <li>alex</li> <li>eric</li> </ul> </div> </div> <script> function AddElement(ths) { // 获取输入的值 var val = ths.previousElementSibling.value; ths.previousElementSibling.value = ""; var commentList = document.getElementById('commentList'); //第一种形式,字符串方式 //var str = "<li>" + val + "</li>"; // 'beforeBegin'、 'afterBegin'、 'beforeEnd'、 'afterEnd' // beforeEnd内部最后 // beforeBegin 外部上边 //afterBegin 内部贴身 //afterEnd 外部贴墙 //commentList.insertAdjacentHTML("beforeEnd",str); //第二种方式,元素的方式 var tag = document.createElement('li'); tag.innerText = val; var temp = document.createElement('a'); temp.innerText = '百度'; temp.href = "http://etiantian.org"; tag.appendChild(temp); // commentList.appendChild(tag); commentList.insertBefore(tag,commentList.children[1]); } </script> </body> </html>
5、样式操作
var obj = document.getElementById('i1') obj.style.fontSize = "32px"; obj.style.backgroundColor = "red";
<input onfocus="Focus(this);" onblur="Blur(this);" id="search" value="请输入关键字" style="color: gray;" /> <script> function Focus(ths){ ths.style.color = "black"; if(ths.value == '请输入关键字' || ths.value.trim() == ""){ ths.value = ""; } } function Blur(ths){ if(ths.value.trim() == ""){ ths.value = '请输入关键字'; ths.style.color = 'gray'; }else{ ths.style.color = "black"; } } </script>
5.1 cloneNode 深克隆浅克隆 true不带true
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h2 id="h1">333 <span>123</span> <a>123</a> </h2> <div id="container"> <div class="item">1</div> <div class="item">2</div> </div> <script> var h = document.getElementById('h1'); var c = document.getElementById('container'); //c.appendChild(h); var newH = h.cloneNode(true); // 深克隆 // var newH = h.cloneNode(); //浅克隆 console.log(newH) // <h2 id="h1"></h2> 前克隆只是框架 c.appendChild(newH); // 浅克隆不复制文本 </script> </body> </html>
6、位置操作
scrollTop: 滚动条距离顶部高度 scrollHeight 文档高度:div的height自身(包括div的滚轮到底的不可见高度)+padding clientTop 边框高度 clientHeight 可见范围的高度:自身(只是div可见框的高度,滚动后的高度不算)+padding offsetTop 当前标签距离“顶部”的高度 (距离body的高度) 所有的padding border等如果有的话 当前标签距离“上部”(父标签的position不算border)定位标签的高度 (如果父标签有position则是距离父亲距离) offsetHeight 可见范围的高度:自身(可视的高度,滚动后的高度不算)+padding+border
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="margin: 0;"> <div style="height: 20px;background-color: green;"></div> <div style="border: 5px solid pink;padding: 10px;position: relative"> <div> <div id="xo" style="height: 200px;overflow: auto;width: 400px;margin: 0 auto;border: 15px solid red;padding: 3px;" > <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> </div> </div> </div> <script> var i = document.getElementById('xo'); // console.log(i.offsetTop); console.log(i.offsetParent) </script> </body> </html>
i.offsetTop
10
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="margin: 0;"> <div style="height: 20px;background-color: green;"></div> <div style="border: 5px solid pink;padding: 10px;"> <div> <div id="xo" style="height: 200px;overflow: auto;width: 400px;margin: 0 auto;border: 15px solid red;padding: 3px;" > <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> </div> </div> </div> <script> var i = document.getElementById('xo'); // console.log(i.offsetTop); console.log(i.offsetParent) </script> </body> </html>
var i = document.getElementById('xo'); undefined i <div id="xo" style="height: 200px;overflow: auto;width: 400px;margin: 0 auto;border: 15px solid red;padding: 3px;">…</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div></div> i.clientHeight 206 i.offsetHeight 236 i.offsetTop 35 i.scrollHeight 924 i.offsetHeight 236 i.scrollTop 0 i.scrollTop 60 i.clientTop 15
总文档高度 document.documentElement.offsetHeight 当前文档占屏幕高度 document.documentElement.clientHeight 自身高度 tag.offsetHeight 距离上级定位高度 tag.offsetTop 父定位标签 tag.offsetParent 滚动高度 tag.scrollTop /* clientHeight -> 可见区域:height + padding clientTop -> border高度 offsetHeight -> 可见区域:height + padding + border offsetTop -> 上级定位标签的高度 scrollHeight -> 全文高:height + padding scrollTop -> 滚动高度 特别的: document.documentElement代指文档根节点 */
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>返回顶部</title> <style> .hide{ display: none; } .go-top{ position: fixed; right: 10px; bottom: 10px; width: 40px; height: 40px; background-color: #5ea593; color:black; } .c1{ visibility: hidden; } .go-top:hover .c1{ visibility: visible; } </style> </head> <body onscroll="Func();"> <div id="i1" style="height: 2000px"> sdfsd </div> <div id="i2" class="go-top hide" onclick="goTOP();" > <!--<a href="#"></a> 不刷新 下面一样--> <a href="javascript:void(0);" class="c1">返回顶部</a> </div> <script type="text/javascript"> function Func() { var hei = document.body.scrollTop; if (hei>100){ document.getElementById("i2").classList.remove("hide"); }else { document.getElementById("i2").classList.add("hide"); }; }; function goTOP() { document.body.scrollTop = 0; } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>菜单跟随滑轮</title> <style> body{ margin: 0; background-color: #dddddd; } .w{ margin: 0 auto; width: 980px; } .pg-header{ background-color: black; color: white; height: 48px; } .pg-body .menu{ position: absolute; left: 200px; width: 180px; background-color: white; float: left; } .pg-body .fixed{ position: fixed; top: 10px; } .pg-body .content{ position: absolute; left: 385px; right: 200px; background-color: white; float: left; } .pg-body .content .item{ height: 900px; } </style> </head> <body onscroll="Hua();"> <div class="pg-header"> <div class="w"> </div> </div> <div class="pg-body"> <div id="menu" class="menu"> <ul> <li>第一章</li> <li>第二章</li> <li>第三章</li> </ul> </div> <div class="content"> <div class="item">床前明月管</div> <div class="item">疑是地上霜</div> <div class="item">我是郭德纲</div> </div> </div> <script type="text/javascript"> function Hua() { var huagao = document.body.scrollTop var caidan = document.getElementById("menu") if (huagao>48){ caidan.classList.add("fixed") }else { caidan.classList.remove("fixed") } } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; background-color: #dddddd; } .w{ margin: 0 auto; width: 980px; } .pg-header{ background-color: black; color: white; height: 48px; } .pg-body .menu{ position: absolute; left: 200px; width: 180px; background-color: white; float: left; } .pg-body .menu .active{ background-color: #425a66; color: white; } .pg-body .fixed{ position: fixed; top: 10px; } .pg-body .content{ position: absolute; left: 385px; right: 200px; background-color: white; float: left; } .pg-body .content .item{ height: 900px; } </style> </head> <body onscroll="Hua();"> <div class="pg-header"> <div class="w"> </div> </div> <div class="pg-body"> <div id="menu" class="menu"> <ul id="ul12"> <li>第一章</li> <li>第二章</li> <li>第三章</li> </ul> </div> <div id="content" class="content"> <div class="item">床前明月管</div> <div class="item">疑是地上霜</div> <div class="item">我是郭德纲</div> </div> </div> <script type="text/javascript"> function Hua() { var huagao = document.body.scrollTop var caidan = document.getElementById("menu") if (huagao>48){ caidan.classList.add("fixed") }else { caidan.classList.remove("fixed"); var active_chi = document.getElementById("ul12").children; for (var j=0;j<active_chi.length;j++){ active_chi[j].className = "" } }; var items = document.getElementById("content").children; for (var i=0;i<items.length;i++){ var currentItem = items[i]; var currentItemBodyTop = currentItem.offsetTop + currentItem.offsetParent.offsetTop var currentItemWindowTop = currentItemBodyTop - huagao; // 目前item顶部距离窗口顶部 console.log(currentItemWindowTop); var currentHeight = currentItem.offsetHeight; var bottomHeight = currentItemBodyTop + currentHeight; if (currentItemWindowTop <0 && huagao < bottomHeight){ var ziJi = caidan.getElementsByTagName("li")[i]; ziJi.className = "active"; var lis = caidan.getElementsByTagName("li") for (var k=0;k<lis.length;k++){ if (ziJi == lis[k]){ }else { lis[k].classList.remove("active") } } }; continue } } </script> </body> </html>
得到各个属性如下: 网页可见区域宽: document .body.clientWidth; 网页可见区域高: document .body.clientHeight; 网页可见区域宽: document .body.offsetWidth (包括边线的宽); 网页可见区域高: document .body.offsetHeight (包括边线的宽); 网页正文全文宽: document .body.scrollWidth; 网页正文全文高: document .body.scrollHeight; 网页被卷去的高: document .body.scrollTop; 网页被卷去的左: document .body.scrollLeft; 网页正文部分上: window.screenTop; 网页正文部分左: window.screenLeft; 屏幕分辨率的高: window.screen.height; 屏幕分辨率的宽: window.screen.width; 屏幕可用工作区高度: window.screen.availHeight; 屏幕可用工作区宽度:window.screen.availWidth; scrollHeight: 获取对象的滚动高度。 scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离 scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离 scrollWidth:获取对象的滚动宽度 offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度 offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置 offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置 event.clientX 相对文档的水平座标 event.clientY 相对文档的垂直座标 event.offsetX 相对容器的水平坐标 event.offsetY 相对容器的垂直坐标 document .documentElement.scrollTop 垂直方向滚动的值 event.clientX+document .documentElement.scrollTop 相对文档的水平座标+垂直方向滚动的量 Post by molong on 2009-05-19 11:57 PM #1 要获取当前页面的滚动条纵坐标位置,用: document .documentElement.scrollTop; 而不是: document .body.scrollTop; documentElement 对应的是 html 标签,而 body 对应的是 body 标签。
document.body 与document.documentelement
http://renshengkai.blogchina.com/1534285.html
(原来HTML里是document.body --XHTML里是document.documentElement ,都指的是节点(OR元素) ) 在设计页面时可能经常会用到固定层的位置,这就需要获取一些html对象的坐标以更灵活的设置目标层的坐标,这里可能就会用到document .body.scrollTop等属性,但是此属性在xhtml标准网页或者更简单的说是带标签的页面里得到的结果是0,如果不要此标签则一切正常,那么在xhtml页面怎么获得body的坐标呢,当然有办法-使用document .documentElement来取代document .body,可以这样写 例: var top = document .documentElement.scrollTop || document .body.scrollTop; 在javascript里||是个好东西,除了能用在if等条件判断里,还能用在变量赋值上。那么上例等同于下例。 例: var top = document .documentElement.scrollTop ? document .documentElement.scrollTop : document .body.scrollTop; 这么写可以得到很好的兼容性。 相反,如果不做声明的话,document .documentElement.scrollTop反而会显示为0。 得到各个属性如下: 网页可见区域宽: document .body.clientWidth; 网页可见区域高: document .body.clientHeight; 网页可见区域宽: document .body.offsetWidth (包括边线的宽); 网页可见区域高: document .body.offsetHeight (包括边线的宽); 网页正文全文宽: document .body.scrollWidth; 网页正文全文高: document .body.scrollHeight; 网页被卷去的高: document .body.scrollTop; 网页被卷去的左: document .body.scrollLeft; 网页正文部分上: window.screenTop; 网页正文部分左: window.screenLeft; 屏幕分辨率的高: window.screen.height; 屏幕分辨率的宽: window.screen.width; 屏幕可用工作区高度: window.screen.availHeight; 屏幕可用工作区宽度:window.screen.availWidth; scrollHeight: 获取对象的滚动高度。 scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离 scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离 scrollWidth:获取对象的滚动宽度 offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度 offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置 offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置 event.clientX 相对文档的水平座标 event.clientY 相对文档的垂直座标 event.offsetX 相对容器的水平坐标 event.offsetY 相对容器的垂直坐标 document .documentElement.scrollTop 垂直方向滚动的值 event.clientX+document .documentElement.scrollTop 相对文档的水平座标+垂直方向滚动的量 Post by molong on 2009-05-19 11:57 PM #1 要获取当前页面的滚动条纵坐标位置,用: document .documentElement.scrollTop; 而不是: document .body.scrollTop; documentElement 对应的是 html 标签,而 body 对应的是 body 标签。 在标准w3c下,document .body.scrollTop恒为0,需要用document .documentElement.scrollTop来代替; 如果你想定位鼠标相对于页面的绝对位置时,你会发现google里面1000篇文章里面有999.99篇会让你使用event.clientX+document .body.scrollLeft,event.clientY+document .body.scrollTop,如果你发现你的鼠标定位偏离了你的想象,请不要奇怪,这是再正常不过的事情。 ie5.5之后已经不支持document .body.scrollX对象了。 所以在编程的时候,请加上这样的判断 复制代码 if (document.body && document.body.scrollTop && document.body.scrollLeft) { top=document .body.scrollTop; left=document .body.scrollleft; } if (document.documentElement && document.documentElement.scrollTop && document.documentElement.scrollLeft) { top=document.documentElement.scrollTop; left=document.documentElement.scrollLeft; } 复制代码
滚动菜单遗留问题:最后一个div content的高度太小导致上面的div未走完。应该显示最后一个菜单
var a = document.body.offsetHeight; // 如果body的conten又position 或者float的话,body的高度只有那部分没有这些属性的那些内容的高度。 var b = document.getElementById('content').offsetHeight // 获取那些飘起来或则position的内容高度 var c = document.documentElement.clientHeight; //浏览器当前窗口能看到部分高度 如果开了f12 挡住的部分不算 var huaGao = document.body.scrollTop; //是除了当前能看到的窗口(f12挡住的不算)大小的滚轮滚动高度 /* document.documentElement.clientHeight; 346 document.body.offsetHeight; 48 document.getElementById('content').offsetHeight 1900 document.body.scrollTop; 1602 */ 总结得到比较 a+b = c+huagao
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; background-color: #dddddd; } .w{ margin: 0 auto; width: 980px; } .pg-header{ background-color: black; color: white; height: 48px; } .pg-body .menu{ position: absolute; left: 200px; width: 180px; background-color: white; float: left; } .pg-body .menu .active{ background-color: #425a66; color: white; } .pg-body .fixed{ position: fixed; top: 10px; } .pg-body .content{ position: absolute; left: 385px; right: 200px; background-color: white; float: left; } .pg-body .content .item{ height: 900px; } </style> </head> <body onscroll="Hua();"> <div class="pg-header"> <div class="w"> </div> </div> <div class="pg-body"> <div id="menu" class="menu"> <ul id="ul12"> <li>第一章</li> <li>第二章</li> <li>第三章</li> </ul> </div> <div id="content" class="content"> <div class="item">床前明月管</div> <div class="item">疑是地上霜</div> <div class="item" style="height: 100px;">我是郭德纲</div> <div>sd</div> </div> </div> <script> function Hua() { var a = document.body.offsetHeight; var b = document.getElementById('content').offsetHeight var c = document.documentElement.clientHeight; //浏览器当前窗口能看到部分高度 如果开了f12 挡住的部分不算 var huaGao = document.body.scrollTop; //是除了当前能看到的窗口(f12挡住的不算)大小的滚轮滚动高度 /* document.documentElement.clientHeight; 346 document.body.offsetHeight; 48 document.getElementById('content').offsetHeight 1900 document.body.scrollTop; 1602 */ var caiDan = document.getElementById('menu'); if(huaGao>48){ caiDan.classList.add('fixed'); }else{ caiDan.classList.remove('fixed'); var active_chi = document.getElementById("ul12").children; for (var j=0;j<active_chi.length;j++){ active_chi[j].className = "" } } var items = document.getElementById('content').children; for(var i=0;i<items.length;i++){ var currentItem = items[i]; var currentItemBodyTop = currentItem.offsetTop + currentItem.offsetParent.offsetTop; var currentItemWindowTop = currentItemBodyTop - huaGao; console.log(currentItemWindowTop); var currentHeight = currentItem.offsetHeight; var bottomHeight = currentItemBodyTop+currentHeight; console.log((a+b),(c+huaGao)) if ((a+b) == (c+huaGao)){ var mu = document.getElementById('menu').children[0].lastElementChild; var lis = document.getElementById("menu").getElementsByTagName("li"); for (var m=0;m<lis.length;m++){ var current_list = lis[m]; if (current_list.getAttribute("class") == "active"){ current_list.classList.remove("active"); break; }; }; mu.classList.add("active") return } if(currentItemWindowTop<0 && huaGao < bottomHeight){ var ziJi = caiDan.getElementsByTagName('li')[i]; ziJi.className = 'active'; var lis = caiDan.getElementsByTagName('li'); for(var j = 0;j<lis.length;j++){ if (ziJi == lis[j]){ }else { lis[j].classList.remove('active'); } } break; } } } </script> </body> </html>
7、提交表单
document.geElementById('form').submit()
datatypes w = "http://whattf.org/datatype-draft" # ##################################################################### ## RELAX NG Schema for HTML 5: Global Structure & Metadata # # ##################################################################### ## Root Element: <html> html.elem = element html { html.inner & html.attrs } html.attrs = ( common.attrs & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) html.inner = ( head.elem , body.elem ) ## Metadata Container: <head> head.elem = element head { head.inner & head.attrs } head.attrs = ( common.attrs # & head.attrs.profile? & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) # head.attrs.profile = # attribute profile { # common.data.uris #REVISIT should these be absolute (zero or more) # } head.inner = ( title.elem & base.elem? # REVISIT need a non-schema checker or Schematron & common.inner.metadata # Limit encoding decl position in Schematron ) # head.inner = # ( meta.elem.encoding? # , ( title.elem # & base.elem? # REVISIT need a non-schema checker or Schematron # & common.inner.metadata # ) # ) ## Content Container: <body> body.elem = element body { body.inner & body.attrs } body.attrs = ( common.attrs & ( common.attrs.aria.landmark.application | common.attrs.aria.landmark.document | common.attrs.aria.role.presentation | common.attrs.aria.implicit.document )? & body.attrs.onafterprint? & body.attrs.onbeforeprint? & body.attrs.onbeforeunload? & body.attrs.onhashchange? & body.attrs.onmessage? & body.attrs.onoffline? & body.attrs.ononline? & body.attrs.onpagehide? & body.attrs.onpageshow? & body.attrs.onpopstate? & body.attrs.onstorage? & body.attrs.onunload? ) body.inner = ( common.inner.flow ) body.attrs.onafterprint = attribute onafterprint { common.data.functionbody } body.attrs.onbeforeprint = attribute onbeforeprint { common.data.functionbody } body.attrs.onbeforeunload = attribute onbeforeunload { common.data.functionbody } body.attrs.onhashchange = attribute onhashchange { common.data.functionbody } body.attrs.onmessage = attribute onmessage { common.data.functionbody } body.attrs.onoffline = attribute onoffline { common.data.functionbody } body.attrs.ononline = attribute ononline { common.data.functionbody } body.attrs.onpopstate = attribute onpopstate { common.data.functionbody } body.attrs.onpagehide = attribute onpagehide { common.data.functionbody } body.attrs.onpageshow = attribute onpageshow { common.data.functionbody } body.attrs.onredo = attribute onredo { common.data.functionbody } body.attrs.onresize = attribute onresize { common.data.functionbody } body.attrs.onstorage = attribute onstorage { common.data.functionbody } body.attrs.onundo = attribute onundo { common.data.functionbody } body.attrs.onunload = attribute onunload { common.data.functionbody } ## Document Title: <title> title.elem = element title { title.inner & title.attrs } title.attrs = ( common.attrs & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) title.inner = ( text ) ## Base URI: <base> base.elem = element base { base.inner & base.attrs } base.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & ( ( base.attrs.href & base.attrs.target? ) | base.attrs.target ) & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) base.attrs.href = attribute href { common.data.uri } base.attrs.target = attribute target { common.data.browsing-context-or-keyword } base.inner = ( empty ) ## Global Relationships: <link> link.elem = element link { link.inner & link.attrs } link.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & link.attrs.href & link.attrs.rel & link.attrs.integrity? & shared-hyperlink.attrs.hreflang? & shared-hyperlink.attrs.media? & shared-hyperlink.attrs.type? & link.attrs.sizes? # link.attrs.title included in common.attrs & embedded.content.attrs.crossorigin? & ( common.attrs.aria.role.link | common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) link.attrs.href = attribute href { common.data.uri.non-empty } link.attrs.rel = attribute rel { w:link-rel } link.attrs.integrity = attribute integrity { common.data.integrity } link.attrs.sizes = attribute sizes { w:string "any" | common.data.sizes } link.inner = ( empty ) common.elem.metadata |= link.elem ## Global Style: <style> style.elem = element style { style.inner & style.attrs } style.attrs = ( common.attrs & style.attrs.type? & style.attrs.media? & style.attrs.nonce? # style.attrs.title included in common.attrs & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) style.attrs.type = attribute type { common.data.mimetype } style.attrs.media = attribute media { common.data.mediaquery } style.attrs.nonce = attribute nonce{ string } style.inner = ( common.inner.anything ) common.elem.metadata |= style.elem ## Scoped Style: <style scoped> style.elem.scoped = element style { style.inner & style.scoped.attrs } style.scoped.attrs = ( common.attrs & style.attrs.type? & style.attrs.media? & style.attrs.scoped # style.attrs.title included in common.attrs & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) style.attrs.scoped = attribute scoped { w:string "scoped" | w:string "" } ## Name-Value Metadata: <meta name> meta.name.elem = element meta { meta.inner & meta.name.attrs } meta.name.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & meta.name.attrs.name & meta.name.attrs.content & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) meta.name.attrs.name = attribute name { w:non-empty-string } meta.name.attrs.content = attribute content { string } meta.inner = ( empty ) common.elem.metadata |= meta.name.elem ## "refresh" pragma directive: <meta http-equiv='refresh'> meta.http-equiv.refresh.elem = element meta { meta.inner & meta.http-equiv.refresh.attrs } meta.http-equiv.refresh.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & meta.http-equiv.attrs.http-equiv.refresh & meta.http-equiv.attrs.content.refresh & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) meta.http-equiv.attrs.http-equiv.refresh = attribute http-equiv { w:string "refresh" } meta.http-equiv.attrs.content.refresh = attribute content { common.data.refresh } common.elem.metadata |= meta.http-equiv.refresh.elem # not quite right per spec # if the definition is # reused in another language ## "default-style" pragma directive: <meta http-equiv='default-style'> meta.http-equiv.default-style.elem = element meta { meta.inner & meta.http-equiv.default-style.attrs } meta.http-equiv.default-style.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & meta.http-equiv.attrs.http-equiv.default-style & meta.http-equiv.attrs.content.default-style & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) meta.http-equiv.attrs.http-equiv.default-style = attribute http-equiv { w:string "default-style" } meta.http-equiv.attrs.content.default-style = attribute content { common.data.default-style } common.elem.metadata |= meta.http-equiv.default-style.elem # not quite right per spec # if the definition is # reused in another language ## Content Security Policy pragma directive: <meta http-equiv='content-security-policy'> meta.http-equiv.content-security-policy.elem = element meta { meta.inner & meta.http-equiv.content-security-policy.attrs } meta.http-equiv.content-security-policy.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & meta.http-equiv.attrs.http-equiv.content-security-policy & meta.http-equiv.attrs.content.content-security-policy & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) meta.http-equiv.attrs.http-equiv.content-security-policy = attribute http-equiv { w:string "content-security-policy" } meta.http-equiv.attrs.content.content-security-policy = attribute content { common.data.content-security-policy } common.elem.metadata |= meta.http-equiv.content-security-policy.elem ## "x-ua-compatible" pragma directive: <meta http-equiv='x-ua-compatible'> meta.http-equiv.x-ua-compatible.elem = element meta { meta.inner & meta.http-equiv.x-ua-compatible.attrs } meta.http-equiv.x-ua-compatible.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & meta.http-equiv.attrs.http-equiv.x-ua-compatible & meta.http-equiv.attrs.content.x-ua-compatible & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) meta.http-equiv.attrs.http-equiv.x-ua-compatible = attribute http-equiv { w:string "x-ua-compatible" } meta.http-equiv.attrs.content.x-ua-compatible = attribute content { common.data.x-ua-compatible } common.elem.metadata |= meta.http-equiv.x-ua-compatible.elem ## Inline Character Encoding Statement for HTML: <meta charset> meta.charset.elem = element meta { meta.inner & meta.charset.attrs } meta.charset.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & meta.charset.attrs.charset & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) meta.charset.attrs.charset = attribute charset { (common.data.charset & HTMLonly) | (xsd:string { pattern = "[uU][tT][fF]-8" } & XMLonly ) } ## Inline Character Encoding Statement for HTML: <meta http-equiv='content-type'> meta.http-equiv.content-type.elem = element meta { meta.inner & meta.http-equiv.content-type.attrs } & HTMLonly meta.http-equiv.content-type.attrs = ( common.attrs.basic & common.attrs.i18n & common.attrs.present & common.attrs.other & meta.http-equiv.attrs.http-equiv.content-type & meta.http-equiv.attrs.content.content-type & ( common.attrs.aria.role.presentation | common.attrs.aria.role.menuitem )? ) meta.http-equiv.attrs.http-equiv.content-type = attribute http-equiv { w:string "content-type" } meta.http-equiv.attrs.content.content-type = attribute content { common.data.meta-charset } common.elem.metadata |= ( meta.charset.elem | meta.http-equiv.content-type.elem )
8 默认事件 事件的函数加 return
比如 a标签 的href 为什么一点击就会跳转呢???
说明是又默认事件的,那么对于 自定义的事件比如onclick 的字符串解析成js代码执行 这个a标签元素获取到这个事件的返回值 来进行判断是否执行默认事件。
默认事件的顺序小与 自定义事件的执行顺序
<a href="http://etiantian.org" onclick="return Func();">点我跳转</a> <script type="text/javascript"> function Func() { alert(123); // return true;// 默认为true,不执行默认事件。 自定义 事件顺序大于默认事件顺序。 而 true则会 跳转。 return false;// 默认为true,不执行默认事件。 自定义 事件顺序大于默认事件顺序。 而 true则会执行a标签的 跳转 但是先会执行func。 } </script>
9、其他操作
console.log 输出框 alert 弹出框 confirm 确认框
// URL和刷新 location.href 获取URL 当前页面 location.href = "url" 重定向 location.reload() 重新加载
// 定时器 setInterval 多次定时器 clearInterval 清除多次定时器 setTimeout 单次定时器 clearTimeout 清除单次定时器
定时器是在函数最后才执行的
停止定时器是 clearinterval
function Interval() { s1 = setInterval(function () { console.log(123) },1000) s2 = setInterval(function () { console.log(123) },1000) console.log("提前1") // 定时器是在函数最后才执行的 } function StopInterval() { clearInterval(s1) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清除 确认 跳转 定时器</title> </head> <body> <form id="fom" action="http://www.sogou.com/web?" method="get"> <input name="querry" type="text"> <input type="button" onclick="SubmitForm();" value="提交"> </form> <hr> <input type="button" value="confirm" onclick="Firm();"> <input type="button" value="Interval" onclick="Interval();"> <input type="button" value="StopInterval" onclick="StopInterval();"> <div> <input type="button" value="删除" onclick="Delet();"> <input type="button" value="保留状态" onclick="UnDelet();"> <div id="status"></div> </div> <script type="text/javascript"> function Firm() { var r = confirm("字符串") // 会获取返回值 console.log(r) } function f1() { console.log(1234) } </script> </body> </html>
保留删除状态5s 跟qq邮箱类似 德已删除德方式
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>清除 确认 跳转 定时器</title> 6 </head> 7 <body> 8 <form id="fom" action="http://www.sogou.com/web?" method="get"> 9 <input name="querry" type="text"> 10 <input type="button" onclick="SubmitForm();" value="提交"> 11 </form> 12 13 <hr> 14 15 <input type="button" value="confirm" onclick="Firm();"> 16 <input type="button" value="Interval" onclick="Interval();"> 17 <input type="button" value="StopInterval" onclick="StopInterval();"> 18 19 <div> 20 <input type="button" value="删除" onclick="Delete();"> 21 <input type="button" value="保留状态" onclick="UnDelet();"> 22 <div id="status"></div> 23 </div> 24 25 <script type="text/javascript"> 26 function UnDelete() { 27 clearTimeout(t1); 28 } 29 function Delete() { 30 document.getElementById("status").innerText = "已删除"; 31 t1 = setInterval(ClearStatus,5000) 32 } 33 function ClearStatus() { 34 document.getElementById("status").innerText = ""; 35 36 } 37 function SubmitForm() { 38 document.getElementById("fom").submit(); 39 } 40 function Firm() { 41 var r = confirm("字符串") 42 console.log(r) 43 } 44 function f1() { 45 console.log(1234) 46 } 47 function Interval() { 48 s1 = setInterval(function () { 49 console.log(123) 50 },1000) 51 s2 = setInterval(function () { 52 console.log(123) 53 },1000) 54 console.log("提前1") // 定时器是在函数最后才执行的 55 } 56 function StopInterval() { 57 clearInterval(s1) 58 } 59 60 </script> 61 62 </body> 63 </html>
作用域
js 三个特点: 1无块级作用域 2 提前声明 3 作用域链
看下面 会打印什么呢??
答案是打印 3
由于定时器是放在最后执行, 所以for循环生成3个 定时器,最后执行,获取i,而循环完后i为 3 。故此 每次定时器打印3个3
<script> function f1() { for (var i=0;i<3;i++){ // 定时器会放在迭代器最后执行,会产生三个定时器,一次循环产生一个定时器,但是要放在for循环最后执行。跟时间秒数 是否为0无关 。 setInterval(function () { console.log(i) },0) } } f1(); </script>
扩展如何将参数传入给定时器呢?? 打印1 2 3 自执行函数
<script> function f1() { for (var i=0;i<3;i++){ setInterval((function (i) { console.log(i) })(i),1000) } } f1(); </script>
扩展 python 的作用域链 应用 lambda 列表推倒式
#lambda def f1(): return i # 等同于 f1 = lambda : i
列表推倒式
# 列表推到式 n = [n+10 for n in range(9) if n >5]
print(n)
块级作用域。
# 而 li = [lambda :x for x in range(10)] print(li[0]()) # 为9
等同于
#!/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ = 'liujianzuo' li = [] for i in range(10): def f1(): return i li.append(f1) print(li[0]()) # 输出为 9 根据作用域链 f1 未执行,因此变量i未赋值。 但是最后执行li[0]()回调f1() return i 这时候就需要向上查找了,i 最后为9
三 事件
HTML DOM Event 对
Event 对象
Event 对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。
事件通常与函数结合使用,函数不会在事件发生前被执行!
事件句柄 (Event Handlers)
HTML 4.0 的新特性之一是能够使 HTML 事件触发浏览器中的行为,比如当用户点击某个 HTML 元素时启动一段 JavaScript。下面是一个属性列表,可将之插入 HTML 标签以定义事件的行为。
属性 | 此事件发生在何时... |
---|---|
onabort | 图像的加载被中断。 |
onblur | 元素失去焦点。 |
onchange | 域的内容被改变。 |
onclick | 当用户点击某个对象时调用的事件句柄。 |
ondblclick | 当用户双击某个对象时调用的事件句柄。 |
onerror | 在加载文档或图像时发生错误。 |
onfocus | 元素获得焦点。 |
onkeydown | 某个键盘按键被按下。 |
onkeypress | 某个键盘按键被按下并松开。 |
onkeyup | 某个键盘按键被松开。 |
onload | 一张页面或一幅图像完成加载。 |
onmousedown | 鼠标按钮被按下。 |
onmousemove | 鼠标被移动。 |
onmouseout | 鼠标从某元素移开。 |
onmouseover | 鼠标移到某元素之上。 |
onmouseup | 鼠标按键被松开。 |
onreset | 重置按钮被点击。 |
onresize | 窗口或框架被重新调整大小。 |
onselect | 文本被选中。 |
onsubmit | 确认按钮被点击。 |
onunload | 用户退出页面。 |
鼠标 / 键盘属性
属性 | 描述 |
---|---|
altKey | 返回当事件被触发时,"ALT" 是否被按下。 |
button | 返回当事件被触发时,哪个鼠标按钮被点击。 |
clientX | 返回当事件被触发时,鼠标指针的水平坐标。 |
clientY | 返回当事件被触发时,鼠标指针的垂直坐标。 |
ctrlKey | 返回当事件被触发时,"CTRL" 键是否被按下。 |
metaKey | 返回当事件被触发时,"meta" 键是否被按下。 |
relatedTarget | 返回与事件的目标节点相关的节点。 |
screenX | 返回当某个事件被触发时,鼠标指针的水平坐标。 |
screenY | 返回当某个事件被触发时,鼠标指针的垂直坐标。 |
shiftKey | 返回当事件被触发时,"SHIFT" 键是否被按下。 |
标准 Event 属性
下面列出了 2 级 DOM 事件标准定义的属性。
属性 | 描述 |
---|---|
bubbles | 返回布尔值,指示事件是否是起泡事件类型。 |
cancelable | 返回布尔值,指示事件是否可拥可取消的默认动作。 |
currentTarget | 返回其事件监听器触发该事件的元素。 |
eventPhase | 返回事件传播的当前阶段。 |
target | 返回触发此事件的元素(事件的目标节点)。 |
timeStamp | 返回事件生成的日期和时间。 |
type | 返回当前 Event 对象表示的事件的名称。 |
标准 Event 方法
下面列出了 2 级 DOM 事件标准定义的方法。IE 的事件模型不支持这些方法:
方法 | 描述 |
---|---|
initEvent() | 初始化新创建的 Event 对象的属性。 |
preventDefault() | 通知浏览器不要执行与事件关联的默认动作。 |
stopPropagation() | 不再派发事件。 |
<html> <head> <script type="text/javascript"> function isKeyPressed(event) { if (event.ctrlKey==1) { alert("The CTRL key was pressed!") } else { alert("The CTRL key was NOT pressed!") } } </script> </head> <body onmousedown="isKeyPressed(event)"> <p>Click somewhere in the document. An alert box will tell you if you pressed the CTRL key or not.</p> </body> </html>
<html> <head> <script type="text/javascript"> function show_coords(event) { x=event.clientX y=event.clientY alert("X 坐标: " + x + ", Y 坐标: " + y) } </script> </head> <body onmousedown="show_coords(event)"> <p>请在文档中点击。一个消息框会提示出鼠标指针的 x 和 y 坐标。</p> </body> </html>