# DOM

Document Object Model

DOM定义了表示和修改文档所需的方法。DOM对象即为宿主对象,由浏览器厂商定义,用来操作html和xml功能的一类对象的集合。也有人称DOM是对HTML以及XML的标准编程接口

# DOM例子

# 计数器实现点击事件变色方块

<div></div>
1
var div = document.getElementsByTagName('div')[0];
div.style.width = "100px";
div.style.height = "100px";
div.style.backgroundColor = "red";
var count = 0;
div.onclick = function () {
    count ++;
    if(count % 2 == 1) {
        this.style.backgroundColor = "green";
    }else{
        this.style.backgroundColor = "red";
    }
}
//如果写三个色的话就%3
// this代表谁绑定的函数,此时this就是div
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 选项卡

<div class="wrapper">
    <button class="active">Taylor</button>
    <button>Smile</button>
    <button>hat</button>
    <div class="content" style="display:block;"></div>
    <div class="content"></div>
    <div class="content"></div>
</div>
1
2
3
4
5
6
7
8
    * {
        margin: 0;
        padding: 0;
    }
    .wrapper div {
        display: none;
        width: 200px;
        height: 200px;
    }

    .active {
        background-color: rgba(0,0,0,.5);
    }
    .wrapper button {
        width: 65px;
        height: 20px;
    }
    
    .wrapper div:nth-of-type(1) {
        background: url(../images/mei.png) no-repeat;
        background-size: 200px 200px;
    }
     .wrapper div:nth-of-type(2) {
        background: url(../images/xiaolian.jpg) no-repeat;
        background-size: 200px 200px;
    }
    .wrapper div:nth-of-type(3) {
        background: url(../images/maozi.jpg) no-repeat;
        background-size: 200px 200px;
    }
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
29
30
var btn=document.getElementsByTagName('button');
var div=document.getElementsByClassName('content')
    for (var i = 0; i < btn.length; i++) {
        (function (n) {
            btn[n].onclick = function () {
            for (var j = 0; j < btn.length; j++) {
                btn[j].className = "";
                div[j].style.display = "none";
            }
            this.className = "active";
            div[n].style.display = "block"
//因为这里的i想要实现上面的btn[n]点击就出现,
//由于上面的btn[n]里面的值在循环还不确定,
//所以要写一个立即执行函数。将每次的下标i传到n
                }
            }(i))
        }
//for循环给每一个button加事件
//当一个button被点击,那么就执行一个函数。
//函数里面首先让自己的btn去掉class类,
//然后class类名等于active,所有的div的属性变成none
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 效果