zoukankan      html  css  js  c++  java
  • python基础-第十一篇-11.2DOM为文档操作

      文档对象模型(DOM)是一种用于HTML和XML文档的编程接口

    节点类型

    • 12种节点类型都有NodeType属性来表明节点类型

    节点关系

        <div id="t">
            <span></span>
            <span id="s">
                <a></a>
                <h1>Nick</h1>
            </span>
            <p></p>
        </div>
    
        <script>
            var t = document.getElementById("t");
            console.log(t.nodeType,t.nodeName,t.nodeValue);  //1 "DIV" null
            console.log(t.parentNode);  //<body>...</body>
            console.log(t.childNodes);  //[text, span, text, span#s, text, p, text]
            console.log(t.children);  //[span, span#s, p, s: span#s]
    
            var s = document.getElementById("s");
            console.log(s.previousSibling);  //#text, Node 对象形式
            console.log(s.previousElementSibling);  //<span></span>
            console.log(s.nextSibling);  //#text
            console.log(s.nextElementSibling);  //<p></p>
            console.log(s.firstchild);  //#text
            console.log(s.firstElementChild);  //<a></a>
            console.log(s.lastChild);  //#text
            console.log(s.lastElementChild);  //<h1>Nick</h1>
    
            console.log(t.childElementCount);  //3
            console.log(t.ownerDocument);  //#document
        </script>
    

    注:children和childNodes区别--childNodes包含文本,所以循环获取标签时需要注意,可以用 对象.nodeType这属性来判断是否为标签,当值为1时,就为标签

        <div>hello
            <div class="c1" id="11">11111<a href="http://www.baidu.com">点我</a></div>
            <div class="c1">2222222</div>
            <div class="c1">3333333</div>
        </div>
        <div>4444444</div>
        <div>55555555</div>
    
        <script>
            var li = document.getElementById('11');
            var p1_text = li.parentNode;//含文本
            console.log(p1_text);
            var p1 = li.parentElement; //不含文本
            console.log(p1);
    
            var child_node = p1_text.childNodes;
            for(var j=0;j<child_node.length;j++){
                console.log('序号:',j);
                var current_node = child_node[j];
                if(current_node.nodeType == 1){
                    console.log(current_node);
                }else{
                    console.log('===',current_node);
                }
            }
    
            var chil = p1.children;
            console.log('chil',chil)
            for(var i=0;i<chil.length;i++){
                var current_node = chil[i];
                console.log('序号:',i);
                console.log(current_node.nodeType);
                console.log(current_node);
            }
        </script>
    

    节点关系方法:

    hasChildNodes()  包含一个或多个节点时返回true

    contains()  如果是后代节点返回true

    isSameNode()、isEqualNode()  传入节点与引用节点的引用为同一个对象返回true

    compareDocumentPostion()  确定节点之间的各种关系

    选择器

    • getElementById()  一个参数:元素标签的ID
    • getElementsByTagName()  一个参数:元素标签名
    • getElementsByNmae()  一个参数:name属性名
    • getElementsByClassName()  一个参数:包含一个或多个类名的字符串
    • classList  返回所有类名的数组
    1. add(添加)
    2. remove(删除)
    3. contains(存在返回true,否则返回false)
    4. toggle(存在则删除,否则添加)
    • querySelector()  接收CSS选择符,返回匹配到的第一个元素,没有则null
    • querySelectorAll()  接收CSS选择符,返回一个数组,没有则返回[]
        <div class="t">
            <div></div>
            <div></div>
            <div></div>
        </div>
    
        <script>
            var t = document.getElementsByClassName("t");
            console.log(t);  //[div.t]
            console.log(t[0]);  //<div id="t">...</div>
            console.log(t.length);  //1
        </script>
    
        <div class="t t2 t3"></div>
    
        <script>
            var t = document.getElementsByTagName("div")[0];
            tlist = t.classList;
            console.log(t);  //<div class="t t2 t3"></div>
            console.log(tlist);  //["t", "t2", "t3"]
            tlist.add("t5");
            console.log(tlist.contains("t5"));  //true
            tlist.remove("t5");
            console.log(tlist.contains("t5"));  //false
            tlist.toggle("t5");
            console.log(tlist.contains("t5"));  //true
        </script>
    
    <!--querySelector()-->
        <div class="t t2 t3"></div>
        <div class="t" id="t"></div>
        <div name="nick"></div>
        <script>
            var tT = document.querySelector("div");
            console.log(tT); //<div class="t t2 t3"></div>
            var tI = document.querySelector("#t");
            console.log(tI); //<div class="t" id="t"></div>
            var tC = document.querySelector(".t");
            console.log(tC); //<div class="t t2 t3"></div>
            var tN = document.querySelector("[name]");
            console.log(tN); //<div name="nick"></div>
        </script>
    
    
    <!--querySelectorAll()-->
        <div class="t t2 t3"></div>
        <div class="t" id="t"></div>
        <div name="nick"></div>
        <script>
            var tT = document.querySelectorAll("div");
            console.log(tT); //[div.t.t2.t3, div#t.t, div]
            var tI = document.querySelectorAll("#t");
            console.log(tI); //[div#t.t]
            var tC = document.querySelectorAll(".t");
            console.log(tC); //[div.t.t2.t3, div#t.t]
            var tN = document.querySelectorAll("[name]");
            console.log(tN); //[div]
        </script>
    

    样式操作方法style

     

        <div id="t" style="background-color: yellow;  100px; height: 100px">8</div>
    
        <script>
            var tT = document.getElementById("t");
            console.log(tT.style.cssText); // 100px; height: 100px; background-color: yellow;
            tT.style.cssText = "background-color: yellow;  200px; height: 200px"; //修改属性
            console.log(tT.style.cssText); // 200px; height: 200px; background-color: yellow;
            console.log(tT.style.item("0")); //background-color
            console.log(tT.style.length); //3
            console.log(tT.style.getPropertyValue("background-color")); //yellow
            console.log(tT.style.getPropertyPriority("background-color")); //空字符串
            console.log(tT.style.removeProperty("width")); //200px
            tT.style.setProperty("width","200px",""); //设置属性,第三个值为important优先值,可不写
            
        </script>
    

    表格操作方法

        <script>
            var table = document.createElement("table");
            table.border = "1px";
            table.width = "150px";
    
            var theadt = table.createTHead();
            var tbody = table.createTBody();
    
            var trH0 = theadt.insertRow(0);
            trH0.insertCell(0).appendChild(document.createTextNode("姓名"));
            trH0.insertCell(1).appendChild(document.createTextNode("年龄"));
    
            var trB0 = tbody.insertRow(0);
            var trB1 = tbody.insertRow(1);
            trB0.insertCell(0).appendChild(document.createTextNode("nick"));
            trB0.insertCell(1).appendChild(document.createTextNode("18"));
            trB1.insertCell(0).appendChild(document.createTextNode("jenny"));
            trB1.insertCell(1).appendChild(document.createTextNode("21"));
    
            trB0.deleteCell(1);
    
            console.log(table);
            document.body.appendChild(table);
        </script>
    View Code

    表单操作方法

    • document.forms  获取所有表单
    • .submit  提交表单
        <form action="https:baidu.com/s" method="get">
            <input type="text" name="wd"/>
            <input type="button" value="百度一下" onclick="this.disable=true;BaiDu(this);"/>
        </form>
    
        <script>
            var form = document.forms;  //获取所有表单
            var formone = form[0];
            console.log(1,form);
            console.log(2,formone);
    
            function BaiDu(ths){
                var inputBaiDu = ths;
                inputBaiDu.parentNode.submit();
            }
        </script>
    

    节点

    • ELEMENT  元素节点

    • attributes  属性节点

    1. attributes  获取所有标签属性
    2. getAttribute()  获取标签指定的属性
    3. setAttribute()  设置指定标签属性
    4. removeAttribute()  移除指定标签属性
    5. var s=document.createAttribute("age");  s.nodeValue="18"  创建age属性,设置属性值为18
        <div id="t" class="s1 s2" name="alex"></div>
        <script>
            var t = document.getElementById("t");
    
            console.log(t.attributes);
            console.log(t.attributes.id);
            console.log(t.attributes.class);
    
            console.log(t.attributes.getNamedItem("name"));
            console.log(t.attributes.removeNamedItem("class"));
            console.log(t.attributes.getNamedItem("class"));
            var s = document.createAttribute("age");
            s.nodeValue = "18";
            console.log(t.attributes.setNamedItem(s));
            console.log(t.attributes);
            console.log(t.attributes.item("1"));
        </script>
    
        <div id="t" class="s1 s2" name="alex"></div>
        <script>
            var t = document.getElementById("t");
    
            console.log(t.attributes);
    
            console.log(t.getAttribute("name"));
            t.setAttribute("age",18);
            console.log(t.getAttribute("age"));
            t.removeAttribute("age");
            console.log(t.getAttribute("age"));
        </script>
    
    •  TEXT 文本节点

        <div id="t">
            <div>1</div>
            <div>2</div>
            <div>3</div>
        </div>
        <script>
            var t = document.getElementById("t");
            console.log(t.innerText);
            console.log(t.outerText);
            console.log(t.innerHTML);
            console.log(t.outerHTML);
            console.log(t.textContent);
        </script>
    

      注:当一个标签里没有内嵌标签只有文本时,此时这个标签的innerText和innerHTML值一样,都是标签的文本,当内嵌了标签的时候,innerHTML就是内嵌的这个标签

        <a href="http://www.baidu.com">老男人</a>
        <input id="ss" type="text">
        <select id="sel">
            <option>上海</option>
            <option>北京</option>
        </select>
        <script>
            var obj = document.getElementsByTagName('a')[0];
            console.log(obj);
            console.log(obj.innerText); //‘老男人’
            console.log(obj.innerHTML);//‘老男人’
    
            obj.innerText = '老男孩';
            console.log('替换inneText后--',obj);
            console.log(obj.innerText); //‘老男孩’
    
            obj.innerHTML = 'hello<p>你好</p>'
            console.log('替换innerHTML后--',obj);
            console.log(obj.innerText); //‘你好’
            console.log(obj.innerHTML); //‘<p>你好</p>’
    
            console.log('===============');
            //value 属性值 只有form表番标签才有
            var t = document.getElementById('sel')
            console.log(t.value);
            t.value = '北京';
            console.log(t.value);
    
        </script>
    
    • 文档节点

    位置操作方法

    • scrollTop  滚动条距离顶部的高度
    • scrollHeight:文档高度:自身+padding
    • clientTop  边框高度
    • clientHeight  可见范围的高度:自身+padding
    • offsetTop  当前标签距离“上级”定位标签的高度
    • offsetHeight  可见范围的高度:自身+padding+border

        <div onscroll="scroll">
            <div id="zg" class="zg">
                <div id="dg" class="dg">
    
                </div>
            </div>
        </div>
        <script>
            var zg = document.documentElement.offsetHeight;
            console.log(zg);  //1006(height+border+padding)
            var dg = document.documentElement.clientHeight;
            console.log(dg);  //902 可变文档占屏幕高度
    
            var dgBox = document.getElementById("dg");
            console.log(dgBox.offsetHeight);  //514 (padding、border、自身高度)
            console.log(dgBox.scrollHeight);  //510  文档高度(自身+padding)
            console.log(dgBox.offsetTop);  //20  上级定位标签的高度
            console.log(dgBox.clientTop);  //边框高度
            console.log(dgBox.offsetParent);  //<div id="zg" class="zg">...</div>元素、父级定位标签
    
            function scroll(){
                console.log(document.body.scrollTop);
            }
    

    定时器

    • setInterval  多次定时器
    • clearInterval  清除多次定时器
    • setTimeout  单次定时器
    • clearTimeout  清除单次定时器
        <input type="button" value="Interval" onclick="Interval();"/>
        <input type="button" value="StopInterval" onclick="StopInterval()"/>
        <script>
            function Interval(){
            s1 = setInterval(function(){
                console.log(123);
            },1000);
            s2 = setInterval(function(){
                console.log(456);
            },2000);
            console.log(1);
            }
    
            function StopInterval(){
                clearInterval(s1);
                clearInterval(s2);
            }
        </script>
    

    弹出框

        <div onclick="func()">12</div>
        <script>
    
        function func(){
            var result = prompt("what is your name?","alex");
            if (result != null){
                alert("welcome,"+result);
            }
            console.log(result);
    

    location

     

    其它

    事件操作

    搜索框

      <style>
      .style_before{
       color:gray;
      }
       .style_after{
       color:black;
       }
      </style>



    <!--onfocus鼠标点进去 onblur鼠标移出去--> <input type="text" placeholder="请输入内容" /> <input type="text" onfocus="Focus(this)" onblur="Blur(this)" class="style_before" value="请输入内容"/> <script> function Focus(ths){ if(ths.value == "请输入内容"){ ths.value = ""; ths.className = "style_after"; } } function Blur(ths){ if(ths.value == "请输入内容" || ths.value.trim().length == 0){ ths.value = "请输入内容"; ths.className = "style_before"; } } </script>

    跑马灯

      <div id="str_one" style="height:150px;color:red;font-size:50px;text-align:center;line-height:150px;fonz-weight:bold">
            上 海 自 来 水 水 来 自 海 上
        </div>
        <script>
            setInterval(function (){
            str = document.getElementById("str_one");
            str_text = str.innerText;
    
            first_char = str_text[0];
            sub_char = str_text.slice(1,str_text.length);
            new_str = sub_char + first_char;
    
            str.innerText = new_str;
            },500)
        </script>
    

     

    全选、反选

        <h3>爱好</h3>
        <div>
            <ul id="il">
                <li><input type="checkbox" value="1"/>篮球</li>
                <li><input type="checkbox" value="2"/>足球</li>
                <li><input type="checkbox" value="3"/>排球</li>
            </ul>
        </div>
        <input type="button" onclick="Cheakall()" value="全选"/>
        <input type="button" onclick="cancleall()" value="取消"/>
        <input type="button" onclick="reversll()" value="反选"/>
        <script>
            function Cheakall(){
                var il = document.getElementById("il");
                var cheak = il.getElementsByTagName("input");
                for(var i=0;i<cheak.length;i++){
                    cheak[i].checked = true;
                }
            }
    
            function cancleall(){
                var il = document.getElementById("il");
                var cheak = il.getElementsByTagName("input");
                for(var j=0;j<cheak.length;j++){
                    cheak[j].checked = false;
                }
            }
    
            function reversll(){
                var il = document.getElementById("il");
                var cheak = il.getElementsByTagName("input");
                for(var k=0;k<cheak.length;k++){
                    var current_st = cheak[k].checked
                    if(current_st){
                        cheak[k].checked = false;
                        }else{
                        cheak[k].checked = true;
                        }
                }
            }
        </script>
    

    模态对话框

    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
            display:none;
            }
    
            .c1{
            position:fixed;
            top:0;
            right:0;
            bottom:0;
            left:0;
            background:rgba(0,0,0,.6);
            z-index:2;
            }
    
            .c2{
            position:fixed;
            400px;
            height:300px;
            top:50%;
            left:50%;
            z-index:3;
            margin-top:-150px;
            margin-left:-200px;
            background:white;
            text-align:center;
            padding-top:150px;
            }
        </style>
    </head>
    <body>
        <div><input type="button" value="登录" onclick="hihi()"/></div>
        <div id="cc1" class="c1 hide"></div>
        <div id="cc2" class="c2 hide">
            <div>用户名:<input type="text"/></div>
            <div>密码:<input type="text"/></div>
            <input type="button" value="确定"/>
            <input type="button" value="取消" onclick="hisl()"/>
        </div>
        <script>
            function hihi(){
                document.getElementById("cc1").classList.remove("hide");
                document.getElementById("cc2").classList.remove("hide");
            }
            function hisl(){
                document.getElementById("cc1").classList.add("hide");
                document.getElementById("cc2").classList.add("hide");
            }
        </script>
    </body>
    

     

    书签章节

      1 <!DOCTYPE html>
      2 <html lang="en">
      3 <head>
      4     <meta charset="UTF-8">
      5     <title>Title</title>
      6     <style>
      7         body{
      8             margin: 0;
      9             background-color: #dddddd;
     10         }
     11         .w{
     12             margin: 0 auto;
     13              980px;
     14         }
     15         .pg-header{
     16             background-color: black;
     17             color: white;
     18             height: 48px;
     19         }
     20         .pg-body .menu{
     21             position: absolute;
     22             left: 200px;
     23              180px;
     24             background-color: white;
     25             float: left;
     26         }
     27         .pg-body .menu .active{
     28             background-color: #425a66;
     29             color: white;
     30         }
     31         .pg-body .fixed{
     32             position: fixed;
     33             top: 10px;
     34         }
     35         .pg-body .content{
     36             position: absolute;
     37             left: 385px;
     38             right: 200px;
     39             background-color: white;
     40             float: left;
     41         }
     42         .pg-body .content .item{
     43             height: 900px;
     44         }
     45     </style>
     46 
     47 </head>
     48 <body onscroll="Hua();">
     49     <div class="pg-header">
     50         <div class="w"></div>
     51     </div>
     52     <div class="pg-body">
     53         <div id="menu" class="menu">
     54             <ul>
     55                 <li>第一章</li>
     56                 <li>第二章</li>
     57                 <li>第三章</li>
     58             </ul>
     59         </div>
     60         <div id="content" class="content">
     61             <div class="item">床前明月管</div>
     62             <div class="item">疑是地上霜</div>
     63             <div class="item" style="height: 100px">我是郭德纲</div>
     64         </div>
     65     </div>
     66 
     67     <script>
     68         function Hua() {
     69             var xo = document.getElementById("menu");
     70             var huaGao = document.body.scrollTop;
     71             if (document.body.scrollTop>48){
     72                 xo.classList.add("fixed");
     73             }else {
     74                 xo.classList.remove("fixed");
     75             }
     76 
     77             var bod = document.body.offsetHeight;
     78             var conAbs = document.getElementsByClassName("content")[0].offsetHeight;
     79             var ck = document.documentElement.clientHeight;
     80 //            console.log((bod + conAbs) == (ck + huaGao));
     81             if ((bod + conAbs) == (ck + huaGao)) {
     82                 var lenLi = xo.getElementsByTagName("li");
     83                 for (var i=0;i<lenLi.length;i++){
     84                     if (i == lenLi.length - 1){
     85                         lenLi[i].className = "active";
     86                     }else {
     87                         lenLi[i].className = "";
     88                     }
     89                 }
     90                 return
     91             }
     92 
     93 
     94             var item = document.getElementById("content").children;
     95             for (var i=0;i<item.length;i++){
     96                 var currentItem = item[i];
     97                 var currentItemBodyTop = currentItem.offsetTop + currentItem.offsetParent.offsetTop;
     98                 var currentItemWindowTop = currentItemBodyTop - huaGao;
     99 
    100                 var currentHeight = currentItem.offsetHeight;
    101                 var bottomHeight = currentItemBodyTop + currentHeight;
    102 
    103                 var ziJi = xo.getElementsByTagName("li")[i];
    104                 if (currentItemWindowTop<0 && huaGao < bottomHeight){
    105                     ziJi.className = "active";
    106                 } else {
    107                     ziJi.className = "";
    108                 }
    109 
    110             }
    111         }
    112 
    113 
    114     </script>
    115 </body>
    116 </html>
    117 
    118 书签章节
    View Code

    菜单

    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            ul{
            list-style:none;
            padding:0;
            margin:0;
            }
            ul li{
            float:left;
            background-color: #2459a2;
            color:white;
            padding:8px 10px;
            }
            .clearfix:after{
            display:block;
            content:".";
            height:0;
            visibility:hidden;
            clear:both;
            }
            .hide{
            display:none;
            }
            .tab-menu .title{
            background:#dddddd;
            }
            .tab-menu .title .active{
            background:#0099dd;
            color:black;
            }
            tab-menu .content{
            border:1px solid #dddddd;
            min-height:150px;
            }
            ul li:hover{
            cursor:pointer;
            }
        </style>
    </head>
    <body>
        <div style="400px;margin:0 auto;">
            <div class="tab-menu">
                <div class="title clearfix">
                    <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">1...</div>
                    <div con="h2">2...</div>
                    <div con="h3">3...</div>
                </div>
            </div>
        </div>
    
        <script>
            function show(ths){
                var tar = ths.getAttribute("target");
                var liclass = ths.parentNode.children;
                /*循环父亲的儿子,如果是自己,加活动状态,否则移除*/
                for(var i=0;i<liclass.length;i++){
                    if(liclass[i].getAttribute("target") == tar){
                        liclass[i].classList.add("active");
                    }else{
                        liclass[i].classList.remove("active");
                    }
                }
                var cont = document.getElementById("content").children;
                /*循环内容,如果与暗号对的上,样式上什么都不做,没对上就隐藏*/
                for(var j=0;j<cont.length;j++){
                    if(cont[j].getAttribute("con") == tar){
                        cont[j].className = "";
                    }else{
                        cont[j].className = "hide";
                    }
                }
            }
        </script>
    </body>
    

    返回顶部

    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .go_top{
            position:fixed;
            right:28px;
            bottom:19px;
            38px;
            height:40px;
            background:yellow;
            }
            .hide{
            display:none;
            }
        </style>
    </head>
    <body onscroll="func();">
        <div style="height:2000px;"></div>
        <div id="i2" class="go_top hide">
            <h3 onclick="gotop();">返回顶部</h3>
        </div>
        <script>
            function func(){
                var scrolltop = document.body.scrollTop;
                var ii = document.getElementById("i2");
                if(scrolltop>300){
                ii.classList.remove("hide");
                }else{
                ii.classList.add("hide");
                }
            }
    
            function gotop(){
            document.body.scrollTop = 0;
            }
        </script>
    </body>
    

    详见:http://www.cnblogs.com/suoning/p/5656922.html

  • 相关阅读:
    洛谷 P2616 [USACO10JAN]购买饲料II Buying Feed, II
    洛谷 P3654 First Step (ファーストステップ)
    洛谷 P1223 排队接水
    洛谷 【P1252】马拉松接力赛
    codevs 4927 线段树练习5
    洛谷 P1678 烦恼的高考志愿
    初识 线段树
    开学第一测
    洛谷 P1531 I Hate It
    CSS3 过渡
  • 原文地址:https://www.cnblogs.com/xinsiwei18/p/5771302.html
Copyright © 2011-2022 走看看