【Python之路】第十三篇--DOM

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

一、查找元素

1、直接查找

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       值 => 文本框,下来框 表单标签的值

获取 与 赋值:(其他同理)
text = obj.innerText   =>  获取包含的文本
obj.innerText = '123' 

2、属性

attributes                // 获取所有标签属性  => 字典形式
setAttribute(key,value)   // 设置标签属性
getAttribute(key)         // 获取指定标签属性   => 没有的为null
 
/*
var atr = document.createAttribute("class");
atr.nodeValue="democlass";
document.getElementById('n1').setAttributeNode(atr);
*/

3、class操作

className                // 获取所有类名 => 字符串形式
classList.remove(cls)    // 删除指定类   => 列表形式
classList.add(cls)       // 添加类    
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            ul{
                list-style: none;
                padding: 0;
                margin: 0;
            }
            .title{
                background: #DDDDDD;
            }
            .clearfix:after{
                display: block;
                content: 'x';
                height: 0;
                visibility: hidden;
                clear: both;
            }
            ul li{
                background: blue;
                color: white;
                float: left;
                padding: 8px 10px;
            }
            .content{
                border: 1px solid #DDDDDD;
                min-height: 200px;
            }
            .active{
                background-color: white;
                color: #000000;
            }
            .dis-con{
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="tab-menu">
            <div class="title clearfix">
                <ul>
                    <li  class="active" target='d1' onclick="Show(this)">价格趋势</li>
                    <li  target='d2'  onclick="Show(this)">市场分布</li>
                    <li  target='d3'  onclick="Show(this)">其他</li>
                </ul>
            </div>
            
            <div class="content" id='content'>
                <div con='d1'>content1</div>
                <div class="dis-con" con='d2'>content2</div>
                <div class="dis-con" con='d3'>content3</div>
            </div>
        </div>
        
        
        <script type="text/javascript">
            function Show(obj){
                var target = obj.getAttribute('target');
                var menu = obj.parentElement.children;
                for(var i=0;i<menu.length;i++){
                    if(menu[i] == obj){
                        obj.className='active';
                    }else{
                        menu[i].removeAttribute('class');
                    }
                }
                //操作内容
                var con_node = document.getElementById('content');
                con = con_node.children;
                for(var j=0;j<con.length;j++){
                    var attr = con[j].getAttribute('con');
                    if(attr == target){
                        con[j].classList.remove('dis-con');
                    }else{
                        con[j].classList.add('dis-con');
                    }
                }
            }
            
            
        </script>
    </body>
</html>
demo

4、标签操作

a.创建标签

// 方式一
var tag = document.createElement('a')
tag.innerText = "alex"
tag.className = "c1"
tag.href = "http://www.cnblogs.com/5poi"
 
// 方式二
var tag = "<a class='c1' href='http://www.cnblogs.com/5poi'>5poi</a>"

b.操作标签

// 方式一
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])   # 指定在xxx[1]前面插入

//移动
obj.appendChild(div)
//克隆
obj.cloneNode(true)  true => 表示克隆里面全部东西  默认:false只克隆标签
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <p> test 1:</p>
        <div>
            <input type="text" />
            <input type="button" value="提交"  onclick="Common(this)"/>
        </div>
        <div>
            <ul id="commonlist">
                <li>alex</li>
                <li>eric</li>
            </ul>
        </div>
        
        <p>test 2:</p>
        <div>
            <input type="text" />
            <input type="button" value="提交"  onclick="Common2(this)"/>
        </div>
        <div>
            <ul id="commonlist2">
                <li>alex</li>
                <li>eric</li>
            </ul>
        </div>
            
        
        <script type="text/javascript">
            function Common(obj){
                var val = obj.previousElementSibling.value;
                obj.previousElementSibling.value ='' ;
                var commonlist = document.getElementById('commonlist');
                //形式一
                var str = '<li>'+val+'</li>';
                commonlist.insertAdjacentHTML('beforeEnd',str);
            }
            function Common2(obj){
                var val = obj.previousElementSibling.value;
                obj.previousElementSibling.value ='' ;
                var commonlist = document.getElementById('commonlist2');
                //形式二
                tag = document.createElement('li');
                tag.innerText = val;
//                commonlist.appendChild(tag);
//                commonlist.insertBefore(tag,commonlist.children[1]);
                
                var temp = document.createElement('a');
                temp.innerText = '百度';
                temp.href = 'http://www.baidu.com';
                tag.appendChild(temp);
                commonlist.appendChild(tag);
                
            }
            

        </script>
    </body>
</html>
demo

5、样式操作

var obj = document.getElementById('i1')
 
obj.style.fontSize = "32px";
obj.style.backgroundColor = "red";

#注意转换:
background-color  =>  backgroundColor 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .input-black{
                color: black;
            }
            .input-gray{
                color: gray;
            }
            
        </style>
    </head>
    <body>
        <input type="text" placeholder="请输入内容" />
        <p>test 1:</p>
        
        <input type="text" class="input-gray" value="请输入内容" onfocus="In(this)" onblur="Out(this)"/>
        
        
        
        
        <script type="text/javascript">
            function In(obj){
                obj.className = 'input-black';
                var current = obj.value;
                if(current == '请输入内容'){
                    obj.value = '';
                }
            }
            function Out(obj){
                
                var current = obj.value;
                if(current == '请输入内容'  || current.trim().length == 0){
                    obj.value = '请输入内容';
                    obj.className = 'input-gray';
                }
            }
            
            
            
        </script>
    </body>
</html>
demo

6、位置操作

特指整个窗口
document.documentElement

总文档高度(文档流)
document.documentElement.offsetHeight
  
当前文档占屏幕高度(视口高度)
document.documentElement.clientHeight
  
可见范围高度: (自身height+border+padding)
tag.offsetHeight
  
当前标签距离文档''顶部''高度(距离上级定位高度)
#如果当前标签,的父标签有position 的话 就是距离position高度
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>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .content{
                height: 2000px;
            }
            .top{
                width: 40px;
                height: 40px;
                background-color: burlywood;
                position: fixed;
                right: 20px;
                bottom: 10px;
            }
            .hide{
                display: none;
            }
        </style>
    </head>
    <body onscroll="f1()">
        <div class="content"></div>
        
        <div class="top" onclick="Gotop()" id='top'>
            <a href="javascript:void(0)">返回顶部</a>
        </div>
        
        <script type="text/javascript">
            function Gotop(){
                document.body.scrollTop = 0 ;
            }
            function f1(){
                var top = document.body.scrollTop;
                var go_top = document.getElementById('top');
                if(top > 100){
                    go_top.classList.remove('hide');
                }else{
                    go_top.classList.add('hide');
                }
            }

        </script>
    </body>
</html>
返回顶部按钮
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            body{
                margin: 0;
                background-color: gray;
                
            }
            .pg-head{
                background: #000000;
                height: 48px;
            }
            .menu{
                position: absolute;
                width: 180px;
                left: 200px;
                background-color: white;
                float: left;
            }
            .content{
                position: absolute;
                width: 180px;
                left: 385px;
                background-color: white;
                float: left;
            }
            .item{
                background-color: white;
                width: 800px;
                height: 900px;
            }
            .pg-body .fixed{
                position: fixed;
                top:10px;
            }
            .pg-body .menu .active{
                background-color: #426ebe;
                color: white;
            }
        </style>
    </head>
    
    <body onscroll="Hua();">
        <div class="pg-head"></div>
        
        <div class="pg-body">
            <div id='menu' class="menu">
                <ul>
                    <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>
        </div>
        
        
        <script type="text/javascript">
            
            function Hua(){
                
                
                var a = document.body.offsetHeight;
                var b = document.getElementById('content').offsetHeight;
                var c = document.documentElement.clientHeight;
                
//                console.log(document.body.scrollTop , document.body.clientHeight , document.body.scrollHeight  );
                var huagao = document.body.scrollTop;
                var menu = document.getElementById('menu');
                if (huagao > 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];
//                    console.log(currentItem.offsetTop);
//                    console.log(currentItem.offsetTop , currentItem.offsetParent.offsetTop);
                    var currentItemBodyTop = currentItem.offsetTop + currentItem.offsetParent.offsetTop
//                    console.log(currentItemTop , huagao);
                    var currentItemWindowTop = currentItemBodyTop - huagao ;
                    var currentHeight = items[i].offsetHeight;
//                    console.log(currentItemWindowTop);
                    if(currentItemWindowTop < 0 && huagao < (currentHeight + currentItemBodyTop)){
                        menu.getElementsByTagName('li')[i].classList.add('active');
                        var li = menu.getElementsByTagName('li');
                        for(var j=0;j<li.length;j++){
                            if(li[j] != menu.getElementsByTagName('li')[i]){
                                li[j].classList.remove('active');
                            }
                        }
                        break;
                    }
                        
                }
                
                //当最后一部分高度不够时!
                if( (a+b) == (huagao+c) ){
                    var mu = document.getElementById('menu').children[0].lastElementChild;
                    var ac = document.getElementById('menu').children[0].getElementsByClassName('active')[0];
                    ac.classList.remove('active');
                    mu.classList.add('active');
                }
                
            }
        </script>
    </body>
</html>
滚动菜单

7、提交表单

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

8、其他操作

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


setInterval(function (){...} , 1000 )  每1秒执行一次这个函数

三、事件

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

  • this

  • event

  • 事件链以及跳出

1.注册事件:
a. <div onxxxx=''>
b.document....on.... =function()

2.this     代指当前正在操作的标签
3.event	   触发当前标签的事件内容

onkeydown='down(this,event)'

console.log(e.KeyCode)

4. 自定义事件>默认事件 (优先级)

如果想要阻止后面事件发生, 需要 return false;
<a href='#' onclick = 'return Func();' ></a> 

如果Func返回false 后面事件不再执行!!!!  

实例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .logo{
                background-color:red ;
                height: 60px;
                color:white;
                font-size: 60px;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="logo" class='logo'>欢迎莅临指导</div>
        
        <script type="text/javascript">
            
            setInterval(function f1(){
                
                var logo = document.getElementById('logo').innerText;
                var first_str = logo[0];
                var sub_str = logo.slice(1,logo.length);
                var new_str = sub_str + first_str;
                document.getElementById('logo').innerText = new_str;
                
            },800)
            

        </script>
        
    </body>
</html>
跑马灯

 

 

练习题:

demo 1:class操作

demo 2:标签操作(多层标签嵌套)

demo 3:样式操作

demo 4:返回顶部按钮

demo 5:滚动菜单

demo 6:事件-跑马灯

1.折叠菜单:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            ul{
                padding: 0;
                margin: 0;
            }
            .father{
                width: 200px;
                height: 500px;
                background-color: gray;
            }
            .hidetitle{
                display:none;
            }
            .title{
                background-color: red;
                cursor: pointer;
            }
            .context{
                background-color: aquamarine;
            }
        </style>
    </head>
    <body>
        <div class="father">
            <div class="item">
                <div class="title" onclick="Show(this)">菜单一</div>
                <div class="context">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
            
            <div class="item">
                <div class="title" onclick="Show(this)">菜单二</div>
                <div class="context hidetitle">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
        
            <div class="item">
                <div class="title" onclick="Show(this)">菜单三</div>
                <div class="context hidetitle">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
        
            <div class="item">
                <div class="title" onclick="Show(this)">菜单四</div>
                <div class="context hidetitle">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <script type="text/javascript">
            function Show(obj){
                
                var pre_node = obj.parentElement;
                obj.nextElementSibling.classList.remove('hidetitle');
                
                var father = obj.parentElement.parentElement;
                var all_son = father.children;
                for(var i=0;i<all_son.length;i++){
                    if (all_son[i] != pre_node){
                        all_son[i].children[1].classList.add('hidetitle');
                    }
                }
            }
        </script>
        
    </body>
</html>
View Code

posted @ 2017-01-24 22:22  5_FireFly  阅读(453)  评论(0编辑  收藏  举报
web
counter