zoukankan      html  css  js  c++  java
  • DOM

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

    一、查找元素

    1、直接查找

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

    2、间接查找

    parentNode          // 父节点
    childNodes          // 所有子节点
    firstChild          // 第一个子节点
    lastChild           // 最后一个子节点
    nextSibling         // 下一个兄弟节点
    previousSibling     // 上一个兄弟节点
    
    #上面的方法含文本
     
    # 下面的方法不含文本
    
    parentElement           // 父节点标签元素
    children                // 所有子标签
    firstElementChild       // 第一个子标签元素
    lastElementChild        // 最后一个子标签元素
    nextElementtSibling     // 下一个兄弟标签元素
    previousElementSibling  // 上一个兄弟标签元素
    

    二、操作

    1、内容

    innerText   文本
    outerText
    innerHTML   HTML内容
    outerHTML  
    value       值
    

    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</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-color: #dddddd;
            }
            .tab-menu .title .active{
                background-color: #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" class="hide">2...</div>
                    <div con="h3" class="hide">3...</div>
                </div>
            </div>
        </div>
    
        <script>
            function Show(ths) {
                var Showli = ths;
                var littarget = Showli.getAttribute("target");
                var liclass = Showli.parentNode.children;
                for (var i=0;i<liclass.length;i++) {
                    if (liclass[i].getAttribute("target") == littarget) {
                        liclass[i].classList.add("active");
                    }else {
                        liclass[i].classList.remove("active");
                    }
                }
                var liycontent = document.getElementById("content").children;
                for (var i=0;i<liycontent.length;i++) {
                    if (liycontent[i].getAttribute("con") == littarget) {
                        liycontent[i].className = "";
                    }else {
                        liycontent[i].className = "hide";
                    }
                }
            }
        </script>
    </body>
    </html>
    实例:菜单栏

    3、class操作

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

    4、标签操作

    a.创建标签

    1
    2
    3
    4
    5
    6
    7
    8
    // 方式一
    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.操作标签

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 方式一
    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])
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <div >
            <input type="text">
            <input type="button" value="添加" onclick="addElement(this)">
        </div>
        <div>
            <ul id="commentList">
                <li>alex</li>
                <li>eric</li>
            </ul>
        </div>
        <script>
            function addElement(arg) {
                // 拿到输入的值
                var content = arg.previousElementSibling.value;
                arg.previousElementSibling.value = '';
                var li = document.getElementById("commentList");
                var str = "<li>" + content + "</li>";
                /*
                beforeEnd   内部最后
                beforeBegin 外部上边
                afterBegin  内部上面
                afterEnd    外部下边
                */
                li.insertAdjacentHTML("afterBegin",str);
            }
        </script>
    </body>
    </html>
    实例:插入一项

    5、样式操作

    1
    2
    3
    4
    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>
    实例:请输入关键字

    6、位置操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    总文档高度
    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</title>
        <style>
            body{
                margin: 0;
            }
            .pg-header {
                height: 48px;
                background-color:black;
                color: white;
            }
            .w{
                margin: 0 auto;
                980px;
            }
            .pg-body{
                background-color: #dddddd;
            }
            .pg-body .menu{
                float: left;
                position: absolute;
                left: 200px;
                180px;
                background-color: #00AA88;
            }
            .pg-body .menu .active{
                background-color: white;
                color: black;;
            }
            .pg-body .fixed{
                position: fixed;
                top:0px;
                left: 200px;
            }
            .pg-body .content{
                float: left;
                position: absolute;
                left: 385px;
                right: 200px;
                background-color: #f2dede;
            }
            .pg-body .item{
                height:800px;
                border: 1px black solid;
            }
        </style>
    </head>
    <body onscroll="hua();">
        <div class="pg-header">
            <div class="w"></div>
        </div>
        <div class="pg-body">
            <div class="menu" id="menu">
                <ul>
                    <li>first chapter</li>
                    <li>second chapter</li>
                    <li>thrid chapter</li>
                </ul>
            </div>
            <div class="content" id="content">
                <div class="item">床前明月光</div>
                <div class="item">疑是地上霜</div>
                <div class="item" style="height: 200px;">我是郭德纲</div>
            </div>
        </div>
        <script>
            function hua() {
                var huaGan = document.body.scrollTop;
                var menu = document.getElementById("menu");
                if(huaGan > 48){
                    menu.classList.add("fixed");
                }else{
                    menu.classList.remove("fixed")
                }
    
                var  items = document.getElementById("content").children;
                for(var i=0; i<items.length; i++){
                    var currentItem = items[i];
    //                当前item离页面顶部的距离
                    var currentItemBodyTop = currentItem.offsetTop + currentItem.offsetParent.offsetTop;
    //                console.log(currentItemBodyTop);
    //                当前item离页面顶部距离相对于滑动整个网页的大小,大于则还未滑到,小于则已越过
                    var currentItemWidowTop = currentItemBodyTop - huaGan;
    //                    判断这一章节是否已经看完
                    var currentHeight = currentItem.offsetHeight;
                    var bottomHeight = currentHeight + currentItemBodyTop;
                    if(currentItemWidowTop < 0 && huaGan < bottomHeight){
                        var self = menu.getElementsByTagName("li")[i];
                        self.className = 'active';
                        var brothers = menu.getElementsByTagName("li");
                        for (var j=0; j<brothers.length; j++){
                            if(self == brothers[j]){
                                
                            }else{
                                brothers[j].classList.remove("active");
                            }
                        }
    
    //                    整个页面的总长度 = 滑轮大小 + 窗口大小
    //                    整个页面的总长度 = body大小(如果没有绝对定位)
                        var wholePageHeight = document.body.scrollHeight;
    //                    窗口大小
                        var widowheight = document.documentElement.clientHeight;
                        console.log(wholePageHeight,huaGan,widowheight);
    //                    1854 1199 655
                        if(huaGan + widowheight == wholePageHeight) {
                            var last = brothers[brothers.length - 1];
                            for (var j = 0; j < brothers.length; j++) {
                                if (last == brothers[j]) {
                                    last.className = 'active';
                                } else {
                                    brothers[j].classList.remove("active");
                                }
                            }
                        }
                        break;
                    }
                }
    
    
            }
        </script>
    </body>
    </html>
    实例:随拖动改变的菜单

    7、提交表单

    1
    document.geElementById('form').submit()

    8、其他操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    console.log                 输出框
    alert                       弹出框
    confirm                     确认框
      
    // URL和刷新
    location.href               获取URL
    location.href = "url"       重定向
    location.reload()           重新加载
      
    // 定时器
    setInterval                 多次定时器
    clearInterval               清除多次定时器
    setTimeout                  单次定时器
    clearTimeout                清除单次定时器
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form id="fom" action="https://www.sogou.com/web?" method="get">
            <input name="query" type="text">
            <input type="button" onclick="SubmitForm();" value="提交">
        </form>
        <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="Delete();">
            <input type="button" value="keep status" onclick="unDelete();">
            <div id="status"></div>
        </div>
        <script>
            function SubmitForm() {
                document.getElementById("fom").submit();
                
            }
            function Firm() {
                var r = confirm("stupid");
    //            # 返回true or false
                console.log(r);
            }
            function Interval() {
    //            # caution golbal arg
                s1 = setInterval(function () {
                    console.log(123);
                },1000);
            }
            function StopInterval() {
                clearInterval(s1);
    
            }
            function Delete() {
                document.getElementById("status").innerText = "Already deleted";
                time = setTimeout(function () {
                    document.getElementById("status").innerText = "";
                },4000);
            }
            function unDelete() {
                clearTimeout(time);
            }
        </script>
    </body>
    </html>
    实例:定时器的应用

    三、事件

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

    • 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>欢迎blue shit莅临指导&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>
    跑马灯
    <!DOCTYPE html>
    <html lang="en">
    <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-color: 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>
    </html>
    模态对话框
  • 相关阅读:
    Kubernetes——安装GlusterFS分布式文件系统
    Jenkins从入门到精通——SonarQube:持续代码质量检查
    Jenkins从入门到精通——代码质量
    Redis从入门到精通——Redis数据类型——1、字符串(String)命令
    Redis从入门到精通——Redis客户端
    并发查询ElasticSearch, 根据分片来实现
    Golang开源定时任务调度框架robfig/cron优化
    解决Ubuntu17.04以上系统,yarn init报错
    Angularjs中的$q详解
    总结那些有默认margin,padding值的html标签
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6510785.html
Copyright © 2011-2022 走看看