首页 > 代码库 > DOM

DOM

文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口。它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。我们最为关心的是,DOM把网页和脚本以及其他的编程语言联系了起来。DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容。

查找元素

直接查找

document.getElementById             根据ID获取一个标签document.getElementsByName          根据name属性获取标签集合document.getElementsByClassName     根据class属性获取标签集合document.getElementsByTagName       根据标签名获取标签集合

间接查找

parentNode          // 父节点childNodes          // 所有子节点firstChild          // 第一个子节点lastChild           // 最后一个子节点nextSibling         // 下一个兄弟节点previousSibling     // 上一个兄弟节点 parentElement           // 父节点标签元素children                // 所有子标签firstElementChild       // 第一个子标签元素lastElementChild        // 最后一个子标签元素nextElementtSibling     // 下一个兄弟标签元素previousElementSibling  // 上一个兄弟标签元素

操作

内容

innerText   文本outerTextinnerHTML   HTML内容innerHTML  value       值

属性

attributes                // 获取所有标签属性setAttribute(key,value)   // 设置标签属性getAttribute(key)         // 获取指定标签属性 /*var atr = document.createAttribute("class");atr.nodeValue="http://www.mamicode.com/democlass";document.getElementById(‘n1‘).setAttributeNode(atr);*/
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title></head><body>    <input type="button" value="http://www.mamicode.com/全选"  onclick="CheckAll();"/>    <input type="button" value="http://www.mamicode.com/取消" onclick="CancelAll();"/>    <input type="button" value="http://www.mamicode.com/反选" 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>

class操作

className                // 获取所有类名classList.remove(cls)    // 删除指定类classList.add(cls)       // 添加类

标签操作

创建标签// 方式一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.mamicode.com/‘http://www.cnblogs.com/wupeiqi‘>wupeiqi"操作标签// 方式一var obj = "<input type=‘text‘ />";xxx.insertAdjacentHTML("beforeEnd",obj);xxx.insertAdjacentElement(‘afterBegin‘,document.createElement(‘p‘)) //注意:第一个参数只能是‘beforeBegin‘、 ‘afterBegin‘、 ‘beforeEnd‘、 ‘afterEnd‘ // 方式二var tag = document.createElement(‘a‘)xxx.appendChild(tag)xxx.insertBefore(tag,xxx[1])样式操作var obj = document.getElementById(‘i1‘) obj.style.fontSize = "32px";obj.style.backgroundColor = "red";
  <input onfocus="Focus(this);" onblur="Blur(this);" id="search" value="http://www.mamicode.com/请输入关键字" style="color: gray;" />    <script>        function Focus(ths){            ths.style.color = "black";            if(ths.value =http://www.mamicode.com/= ‘请输入关键字‘ || ths.value.trim() ==""){                ths.valuehttp://www.mamicode.com/= "";            }        }        function Blur(ths){            if(ths.value.trim() == ""){                ths.value = http://www.mamicode.com/‘请输入关键字‘;"black";            }        }    </script>

位置操作

总文档高度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代指文档根节点*/
技术分享
 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title></title> 6 </head> 7 <body style="margin: 0;"> 8     <div style="height: 900px;"> 9 10     </div>11     <div style="padding: 10px;">12         <div id="i1" style="height:190px;padding: 2px;border: 1px solid red;margin: 8px;">13                 <p>asdf</p>14                 <p>asdf</p>15                 <p>asdf</p>16                 <p>asdf</p>17                 <p>asdf</p>18         </div>19     </div>20 21     <script>22         var i1 = document.getElementById(i1);23 24         console.log(i1.clientHeight); // 可见区域:height + padding25         console.log(i1.clientTop);    // border高度26         console.log(=====);27         console.log(i1.offsetHeight); // 可见区域:height + padding + border28         console.log(i1.offsetTop);    // 上级定位标签的高度29         console.log(=====);30         console.log(i1.scrollHeight);   //全文高:height + padding31         console.log(i1.scrollTop);      // 滚动高度32         console.log(=====);33 34     </script>35 </body>36 </html>
test
技术分享
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title></head><style>    body{        margin: 0px;    }    img {        border: 0;    }    ul{        padding: 0;        margin: 0;        list-style: none;    }    .clearfix:after {        content: ".";        display: block;        height: 0;        clear: both;        visibility: hidden;    }    .wrap{        width: 980px;        margin: 0 auto;    }    .pg-header{        background-color: #303a40;        -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);        -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);        box-shadow: 0 2px 5px rgba(0,0,0,.2);    }    .pg-header .logo{        float: left;        padding:5px 10px 5px 0px;    }    .pg-header .logo img{        vertical-align: middle;        width: 110px;        height: 40px;    }    .pg-header .nav{        line-height: 50px;    }    .pg-header .nav ul li{        float: left;    }    .pg-header .nav ul li a{        display: block;        color: #ccc;        padding: 0 20px;        text-decoration: none;        font-size: 14px;    }    .pg-header .nav ul li a:hover{        color: #fff;        background-color: #425a66;    }    .pg-body{    }    .pg-body .catalog{        position: absolute;        top:60px;        width: 200px;        background-color: #fafafa;        bottom: 0px;    }    .pg-body .catalog.fixed{        position: fixed;        top:10px;    }    .pg-body .catalog .catalog-item.active{        color: #fff;        background-color: #425a66;    }    .pg-body .content{        position: absolute;        top:60px;        width: 700px;        margin-left: 210px;        background-color: #fafafa;        overflow: auto;    }    .pg-body .content .section{        height: 500px;    }</style><body onscroll="ScrollEvent();"><div class="pg-header">    <div class="wrap clearfix">        <div class="logo">            <a href="#">                <img src="http://core.pc.lietou-static.com/revs/images/common/logo_7012c4a4.pn">            </a>        </div>        <div class="nav">            <ul>                <li>                    <a  href="#">首页</a>                </li>                <li>                    <a  href="#">功能一</a>                </li>                <li>                    <a  href="#">功能二</a>                </li>            </ul>        </div>    </div></div><div class="pg-body">    <div class="wrap">        <div class="catalog">            <div class="catalog-item" auto-to="function1"><a>第1张</a></div>            <div class="catalog-item" auto-to="function2"><a>第2张</a></div>            <div class="catalog-item" auto-to="function3"><a>第3张</a></div>        </div>        <div class="content">            <div menu="function1" class="section">                <h1>第一章</h1>            </div>            <div menu="function2" class="section">                <h1>第二章</h1>            </div>            <div menu="function3" class="section">                <h1>第三章</h1>            </div>        </div>    </div></div>    <script>        function ScrollEvent(){            var bodyScrollTop = document.body.scrollTop;            if(bodyScrollTop>50){                document.getElementsByClassName(catalog)[0].classList.add(fixed);            }else{                document.getElementsByClassName(catalog)[0].classList.remove(fixed);            }        }    </script></body></html>
滚动固定
技术分享
  1 <!DOCTYPE html>  2 <html>  3 <head lang="en">  4     <meta charset="UTF-8">  5     <title></title>  6 </head>  7 <style>  8   9     body{ 10         margin: 0px; 11     } 12     img { 13         border: 0; 14     } 15     ul{ 16         padding: 0; 17         margin: 0; 18         list-style: none; 19     } 20     h1{ 21         padding: 0; 22         margin: 0; 23     } 24     .clearfix:after { 25         content: "."; 26         display: block; 27         height: 0; 28         clear: both; 29         visibility: hidden; 30     } 31  32     .wrap{ 33         width: 980px; 34         margin: 0 auto; 35     } 36  37     .pg-header{ 38         background-color: #303a40; 39         -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2); 40         -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2); 41         box-shadow: 0 2px 5px rgba(0,0,0,.2); 42     } 43     .pg-header .logo{ 44         float: left; 45         padding:5px 10px 5px 0px; 46     } 47     .pg-header .logo img{ 48         vertical-align: middle; 49         width: 110px; 50         height: 40px; 51  52     } 53     .pg-header .nav{ 54         line-height: 50px; 55     } 56     .pg-header .nav ul li{ 57         float: left; 58     } 59     .pg-header .nav ul li a{ 60         display: block; 61         color: #ccc; 62         padding: 0 20px; 63         text-decoration: none; 64         font-size: 14px; 65     } 66     .pg-header .nav ul li a:hover{ 67         color: #fff; 68         background-color: #425a66; 69     } 70     .pg-body{ 71  72     } 73     .pg-body .catalog{ 74         position: absolute; 75         top:60px; 76         width: 200px; 77         background-color: #fafafa; 78         bottom: 0px; 79     } 80     .pg-body .catalog.fixed{ 81         position: fixed; 82         top:10px; 83     } 84  85     .pg-body .catalog .catalog-item.active{ 86         color: #fff; 87         background-color: #425a66; 88     } 89  90     .pg-body .content{ 91         position: absolute; 92         top:60px; 93         width: 700px; 94         margin-left: 210px; 95         background-color: #fafafa; 96         overflow: auto; 97     } 98     .pg-body .content .section{ 99         height: 500px;100         border: 1px solid red;101     }102 </style>103 <body onscroll="ScrollEvent();">104 <div class="pg-header">105     <div class="wrap clearfix">106         <div class="logo">107             <a href="#">108                 <img src="http://core.pc.lietou-static.com/revs/images/common/logo_7012c4a4.pn">109             </a>110         </div>111         <div class="nav">112             <ul>113                 <li>114                     <a  href="#">首页</a>115                 </li>116                 <li>117                     <a  href="#">功能一</a>118                 </li>119                 <li>120                     <a  href="#">功能二</a>121                 </li>122             </ul>123         </div>124 125     </div>126 </div>127 <div class="pg-body">128     <div class="wrap">129         <div class="catalog" id="catalog">130             <div class="catalog-item" auto-to="function1"><a>第1张</a></div>131             <div class="catalog-item" auto-to="function2"><a>第2张</a></div>132             <div class="catalog-item" auto-to="function3"><a>第3张</a></div>133         </div>134         <div class="content" id="content">135             <div menu="function1" class="section">136                 <h1>第一章</h1>137             </div>138             <div menu="function2" class="section">139                 <h1>第二章</h1>140             </div>141             <div menu="function3" class="section">142                 <h1>第三章</h1>143             </div>144         </div>145     </div>146 147 </div>148     <script>149         function ScrollEvent(){150             var bodyScrollTop = document.body.scrollTop;151             if(bodyScrollTop>50){152                 document.getElementsByClassName(catalog)[0].classList.add(fixed);153             }else{154                 document.getElementsByClassName(catalog)[0].classList.remove(fixed);155             }156 157             var content = document.getElementById(content);158             var sections = content.children;159             for(var i=0;i<sections.length;i++){160                 var current_section = sections[i];161 162                 // 当前标签距离顶部绝对高度163                 var scOffTop = current_section.offsetTop + 60;164 165                 // 当前标签距离顶部,相对高度166                 var offTop = scOffTop - bodyScrollTop;167 168                 // 当前标签高度169                 var height = current_section.scrollHeight;170 171                 if(offTop<0 && -offTop < height){172                     // 当前标签添加active173                     // 其他移除 active174                     var menus = document.getElementById(catalog).children;175                     var current_menu = menus[i];176                     current_menu.classList.add(active);177                     for(var j=0;j<menus.length;j++){178                         if(menus[j] == current_menu){179 180                         }else{181                             menus[j].classList.remove(active);182                         }183                     }184                     break;185                 }186 187             }188 189 190         }191     </script>192 </body>193 </html>
滚动菜单
技术分享
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title></head><style>    body{        margin: 0px;    }    img {        border: 0;    }    ul{        padding: 0;        margin: 0;        list-style: none;    }    h1{        padding: 0;        margin: 0;    }    .clearfix:after {        content: ".";        display: block;        height: 0;        clear: both;        visibility: hidden;    }    .wrap{        width: 980px;        margin: 0 auto;    }    .pg-header{        background-color: #303a40;        -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);        -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);        box-shadow: 0 2px 5px rgba(0,0,0,.2);    }    .pg-header .logo{        float: left;        padding:5px 10px 5px 0px;    }    .pg-header .logo img{        vertical-align: middle;        width: 110px;        height: 40px;    }    .pg-header .nav{        line-height: 50px;    }    .pg-header .nav ul li{        float: left;    }    .pg-header .nav ul li a{        display: block;        color: #ccc;        padding: 0 20px;        text-decoration: none;        font-size: 14px;    }    .pg-header .nav ul li a:hover{        color: #fff;        background-color: #425a66;    }    .pg-body{    }    .pg-body .catalog{        position: absolute;        top:60px;        width: 200px;        background-color: #fafafa;        bottom: 0px;    }    .pg-body .catalog.fixed{        position: fixed;        top:10px;    }    .pg-body .catalog .catalog-item.active{        color: #fff;        background-color: #425a66;    }    .pg-body .content{        position: absolute;        top:60px;        width: 700px;        margin-left: 210px;        background-color: #fafafa;        overflow: auto;    }    .pg-body .content .section{        height: 500px;        border: 1px solid red;    }</style><body onscroll="ScrollEvent();"><div class="pg-header">    <div class="wrap clearfix">        <div class="logo">            <a href="#">                <img src="http://core.pc.lietou-static.com/revs/images/common/logo_7012c4a4.pn">            </a>        </div>        <div class="nav">            <ul>                <li>                    <a  href="#">首页</a>                </li>                <li>                    <a  href="#">功能一</a>                </li>                <li>                    <a  href="#">功能二</a>                </li>            </ul>        </div>    </div></div><div class="pg-body">    <div class="wrap">        <div class="catalog" id="catalog">            <div class="catalog-item" auto-to="function1"><a>第1张</a></div>            <div class="catalog-item" auto-to="function2"><a>第2张</a></div>            <div class="catalog-item" auto-to="function3"><a>第3张</a></div>        </div>        <div class="content" id="content">            <div menu="function1" class="section">                <h1>第一章</h1>            </div>            <div menu="function2" class="section">                <h1>第二章</h1>            </div>            <div menu="function3" class="section" style="height: 200px;">                <h1>第三章</h1>            </div>        </div>    </div></div>    <script>        function ScrollEvent(){            var bodyScrollTop = document.body.scrollTop;            if(bodyScrollTop>50){                document.getElementsByClassName(catalog)[0].classList.add(fixed);            }else{                document.getElementsByClassName(catalog)[0].classList.remove(fixed);            }            var content = document.getElementById(content);            var sections = content.children;            for(var i=0;i<sections.length;i++){                var current_section = sections[i];                // 当前标签距离顶部绝对高度                var scOffTop = current_section.offsetTop + 60;                // 当前标签距离顶部,相对高度                var offTop = scOffTop - bodyScrollTop;                // 当前标签高度                var height = current_section.scrollHeight;                if(offTop<0 && -offTop < height){                    // 当前标签添加active                    // 其他移除 active                    // 如果已经到底部,现实第三个菜单                    // 文档高度 = 滚动高度 + 视口高度                    var a = document.getElementsByClassName(content)[0].offsetHeight + 60;                    var b = bodyScrollTop + document.documentElement.clientHeight;                    console.log(a+60,b);                    if(a == b){                        var menus = document.getElementById(catalog).children;                        var current_menu = document.getElementById(catalog).lastElementChild;                        current_menu.classList.add(active);                        for(var j=0;j<menus.length;j++){                            if(menus[j] == current_menu){                            }else{                                menus[j].classList.remove(active);                            }                        }                    }else{                        var menus = document.getElementById(catalog).children;                        var current_menu = menus[i];                        current_menu.classList.add(active);                        for(var j=0;j<menus.length;j++){                            if(menus[j] == current_menu){                            }else{                                menus[j].classList.remove(active);                            }                        }                    }                    break;                }            }        }    </script></body></html>
滚动高度

提交表单

document.geElementById(‘form‘).submit()

其他操作

console.log                 输出框alert                       弹出框confirm                     确认框  // URL和刷新location.href               获取URLlocation.href = "http://www.mamicode.com/url"       重定向location.reload()           重新加载  // 定时器setInterval                 多次定时器clearInterval               清除多次定时器setTimeout                  单次定时器clearTimeout                清除单次定时器

事件

技术分享

对于事件需要注意的要点:

  • this
  • event
  • 事件链以及跳出

this标签当前正在操作的标签,event封装了当前事件的内容。

实例:

技术分享
<!DOCTYPE html><html>    <head>        <meta charset=‘utf-8‘ />        <title></title>                <style>            .gray{                color:gray;            }            .black{                color:black;            }        </style>        <script type="text/javascript">            function Enter(){               var id= document.getElementById("tip")               id.className = black;               if(id.value==请输入关键字||id.value.trim()==‘‘){                    id.value = ‘‘               }            }            function Leave(){                var id= document.getElementById("tip")                var val = id.value;                if(val.length==0||id.value.trim()==‘‘){                    id.value = 请输入关键字                    id.className = gray;                }else{                    id.className = black;                }            }        </script>    </head>    <body>        <input type=‘text‘ class=‘gray‘ id=‘tip‘ value=‘请输入关键字‘ onfocus=‘Enter();‘  onblur=‘Leave();‘/>    </body></html>
搜索框
技术分享
<!DOCTYPE html><html>    <head>        <meta charset=‘utf-8‘ >        <title>欢迎宝强同志莅临指导&nbsp;&nbsp;</title>        <script type=‘text/javascript‘>            function Go(){                var content = document.title;                var firstChar = content.charAt(0)                var sub = content.substring(1,content.length)                document.title = sub + firstChar;            }            setInterval(Go(),1000);        </script>    </head>    <body>        </body></html>
跑马灯

 

DOM