一个人太孤独? 5分钟了解DOM

93 阅读4分钟

DOM 的基本概念及操作

  • DOM(Document Object Model): 文档对象模型
  • 其实就是操作 html 中的标签的一些能力
  • 我们可以操作哪些内容
    • 获取一个元素
    • 移除一个元素
    • 创建一个元素
    • 向页面中添加一个元素
    • 给元素绑定一些事件
    • 获取元素的属性
    • 给元素添加一些 css 样式
    • ...
  • DOM 的核心对象就是 document 对象
  • document 对象是浏览器内置的一个对象, 里面存储这专门用来操作元素的各种方法
  • DOM: 页面中的标签, 我们通过 JS 获取到以后, 就把这个对象叫做 DOM 对象

获取非常规元素

  • document.documentElement 获取html标签
var s = document.documentElement
console.log(s) //会打印欻HTML标签和标签内所有元素
  • document.head
var ss = document.document.head
console.log(ss) //打印head标签和标签内的左右元素
  • document.body
var sss = document.body
console.log(sss)//打印body标签和标签内所有元素

获取常规元素

  • 通过 JS 代码来获取页面中的标签, 获取后我们就可以操作这些标签
    • getElementById *
<body>
    <div id="box"></div>
    <script>
    	var box = document.getElementById('box')
    	console.log(box) // 页面中 ID 为 box 的标签
    </script>
</body>
  • getElementsByClassName
    • 通过元素的class类名获取元素 但是class是关键字 所以是通过className获取
    • 该方法获取到的是一个类数组 哪怕没有元素也是一个空类数组(类数组同样有索引且可以通过索引访问类数组内的元素)
<body>
<div calss="box"></div>
<script>
    var box = document.getElementsByClassName('box')
    console.log(box) // [<div></div>]
    console.log(box[0]) // <div></div>
</script>
</body>
  • getElementsByTagName
    • 通过元素名获取元素 该方法同样的是返回一个类数组
<body>
<div calss="box"></div>
<script>
    var box = document.getElementsByTagName('div')
    console.log(box) // [<div></div>]
</script>
</body>
  • querySelector
    • 该方法获取页面中符合条件的第一个元素 直接获取到元素
```
  • querySelectorAll
    • 该方法获取到符合条件的所有元素 也类数组的形式集合
```

操作属性

innerHTML
* 该方法获取元素的内部结构 
<div>
    <p>
        <span>hello</span>
    </p>
</div>
var div = document.querySelector('div') //获取结构的前提是先获取到元素
var ss = div.innerHTML
console.log(ss)    // <p><span>hello</span></p>
    • 设置元素的内部 html结构
<div>
    <p>
        <span>hello</span>
    </p>
</div>
var div = document.querySelector('div') //获取结构的前提是先获取到元素
div.innerHTML = '结构例如:<div><p></p></div>'
console.log(ss)    // <p><span>hello</span></p>
innerText
* 获取元素内部的文本 只获取文本 不会获取结构 
<div>
  <p>
     hello
      <span>hello</span>
  </p>
</div>
<script>
var div = document.querySelector('div') //获取结构的前提是先获取到元素
var ss = div.innerHTML
console.log(ss)    // hello
                  //   hello
</script>
getAttribute
* 该方法获取元素的属性 前提是要先获取到元素本身 然后使用该方法获取到元素的属性
<div a="10" class="box"></div>

var div = document.querySelector('div')//获取到元素 才可以进一步操作
console.log(div.getAttribute('a'))  // 10
console.log(div.getAttribute('class'))  // box 通过属性 比如class id 获取到对应的类名 或者id名
setAttribute
* 一般来说可以获取到的 一般都可以修改 属性也不例外 可以直接修改
<div></div>

var div = document.querySelector('div')
console.log(div.setAttribute('class', box)) //('属性', 添加的值)
removeAttribute
* 直接移出元素的某个属性
<div a="100" class="box"></div>

var div = document.querySelector('div')
console.log(div.removeAttribute('calss'))
style
* 专门用来个元素添加 css 样式的
* 添加的都是行内样式
<div></div>

var div = document.querySelector('div')
div.style.width = '100px'
div.style.hright = '100px'
div.style.backgroundColor = 'pink'
className
* 专门用来操作元素的 类名
<div class='box'></div>

var div = document.querySelector('div')
console.log(div.className)  // box
div.calssName = 'ceshi'
console.log(div.calssName)  // ceshi
  • 在设置的时候, 不管之前有没有类名, 都会全部被设置的值覆盖
H5 自定义属性
  • 在 H5 自定义属性中 data- 表示该属性是一个自定义属性
  • data- 以后的内容才是属性名
  • = 后面的内容才叫做属性值
  • 每一个元素身上天生自带一个属性, 叫做 dataset, 是一个类似对象的数据结构
  • 内部记录的是该元素身上所有 data- 开头的自定义属性
  • 对于该元素 H5 自定义属性的操作, 就是对这个数据结构的操作(对象操作语法)
<div data-a="100" class="box"></div>

var oDiv = document.querySelector('div')
// 增
oDiv.dataset.age = 18
// 删
delete oDiv.dataset.a
// 查
console.log(oDiv.dataset.age)

案例

  1. 回到顶部
<head>
    <style>
        #header{
            height: 300px;
            width: 100%;
            position: fixed;
            top: -300px;
            background-color: pink;
        }
        #btn{
            width: 100px;
            height: 100px;
            position: fixed;
            right: 20px;
            bottom: 100px;
            background-color: red;
            display: none;
        }
    </style>
</head>
<body>
<div id="header"></div>
<div id="btn"></div>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
        <li>11</li>
        <li>12</li>
        <li>13</li>
        <li>14</li>
        <li>15</li>
        <li>16</li>
        <li>17</li>
        <li>18</li>
        <li>19</li>
        <li>20</li>
        <li>21</li>
        <li>22</li>
        <li>23</li>
        <li>24</li>
        <li>25</li>
        <li>26</li>
        <li>27</li>
        <li>28</li>
        <li>29</li>
        <li>30</li>
        <li>31</li>
        <li>32</li>
        <li>33</li>
        <li>34</li>
        <li>35</li>
        <li>36</li>
        <li>37</li>
        <li>38</li>
        <li>39</li>
        <li>40</li>
        <li>41</li>
        <li>42</li>
        <li>43</li>
        <li>44</li>
        <li>45</li>
        <li>46</li>
        <li>47</li>
        <li>48</li>
        <li>49</li>
        <li>50</li>
        <li>51</li>
        <li>52</li>
        <li>53</li>
        <li>54</li>
        <li>55</li>
        <li>56</li>
        <li>57</li>
        <li>58</li>
        <li>59</li>
        <li>60</li>
        <li>61</li>
        <li>62</li>
        <li>63</li>
        <li>64</li>
        <li>65</li>
        <li>66</li>
        <li>67</li>
        <li>68</li>
        <li>69</li>
        <li>70</li>
        <li>71</li>
        <li>72</li>
        <li>73</li>
        <li>74</li>
        <li>75</li>
        <li>76</li>
        <li>77</li>
        <li>78</li>
        <li>79</li>
        <li>80</li>
        <li>81</li>
        <li>82</li>
        <li>83</li>
        <li>84</li>
        <li>85</li>
        <li>86</li>
        <li>87</li>
        <li>88</li>
        <li>89</li>
        <li>90</li>
        <li>91</li>
        <li>92</li>
        <li>93</li>
        <li>94</li>
        <li>95</li>
        <li>96</li>
        <li>97</li>
        <li>98</li>
        <li>99</li>
        <li>100</li>
    </ul>
</body>
<script>
    var Odiv  = document.getElementById('header')
    // 获取到头部div
    var Btn = document.getElementById('btn')
    // 获取到按钮 也不是按钮 我们要作为按钮的结构
    window.onscroll = function () { //onscorll 事件 本案例需要滚动 所以必须要在滚动事件里面
        if(document.documentElement.scrollTop >= 300){ //判断滚动距离 不一定需要时是300
            Odiv.style.top = 0 // 将head div 的位置放到顶部可见区域
            Btn.style.display = 'block' //显示回到顶部按钮
        }else{//假如滚动距离再次小于300 
            Odiv.style.top = 300 + 'px'//再次隐藏顶部盒子
            Btn.style.display = 'none'//隐藏按钮
        }
        Btn.onclick = function () {
            document.documentElement,scrollTop = 0//点击按钮 时 让滚动距离回到顶部
        }
    }

</script>

  1. 密码可视化
<body>
    <input type="password" id="pwd"> <button id="btn">按钮</button>
    <script>
        var pwd = document.getElementById('pwd')
        //获取到密码输入框
        var btn = document.querySelector('#btn')
        // 获取到按钮
        btn.onclick = function () { //给按钮添加点击事件 这是前提
                if(pwd.getAttribute == password){ //如果type属性为password时 输入的数据是不可见的
                     pwd.setAttribute('type','text') //将其修改为可见输入框 也就是文本输入框
                 }else{
                    pwd.setAttribute('type','password') //再次点击时将文本框重新修改为密码框
                }
            }
    </script>
</body>

  1. 全选
<body>
    <input type="checkbox" id="allBtn">
    <hr>
    <input type="checkbox" class="item"><br>
    <input type="checkbox" class="item"><br>
    <input type="checkbox" class="item"><br>
    <input type="checkbox" class="item"><br>

    <script>
        var allBtn = document.getElementById('allBtn')
        //获取到全选按钮
        var items = [...document.getElementsByClassName('item')]//...是将伪数组拆散开 然后放在数组里面 伪数组就变成啦真数组
        // 获取到多选按钮
        allBtn.onclick = function () { //给全选按钮添加点击事件
                // if(allBtn.checked){ //checked的返回值是布尔值  所以可以去掉判断
                    items.forEach(function (item) {
                        item.checked = allBtn.checked
                        // item.checked = true  if判断语句
                    })
                }
            // } else {
                // item.checked = false //if语句
            // }
    </script>
</body>
</html>
  1. 选项卡
<head>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        ul,
        ol {
            list-style: none;
        }

        .header {
            width: 600px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            background-color: pink;
            display: flex;
        }

        .header li {
            width: 200px;
        }

        .content {
            width: 600px;
            height: 400px;
            line-height: 400px;
            text-align: center;
        }

        .header .active {
            background-color: aquamarine;
        }

        .content li {
            display: none;
            font-size: 50px;
        }

        .content .active {
            display: block;
            background-color: orange;
        }
    </style>
</head>

<body>
    <ul class="header">
        <li>header_1</li>
        <li class="active">header_2</li>
        <li>header_3</li>
    </ul>
    <ol class="content">
        <li>content_1</li>
        <li class="active">content_2</li>
        <li>content_3</li>
    </ol>
<script>
        var HeadLi = [...document.querySelectorAll('.header li')]
        // 获取到li元素
        var contLi = [...document.querySelectorAll('.content li')]
        HeadLi.forEach(function (item,index) {
            item.onclick = function () { //给需要的元素添加点击事件
                HeadLi.forEach(function (hedLi,heDIndex) {
                    hedLi.classList.remove('active') //点击开始 移除所有样式
                        contLi[heDIndex].classList.remove('active')
                        //因为默认有展示 且content盒子下的li与header下的li 是同步展示 所以移除当前位置的cont
                    })
                    hedLi.classList.add('active') //给当前点击的元素添加样式
                    contLi[index].classList.add('active')//展示对应的content盒子
                }
            })
</script>
</body>
  1. 渲染表格
<body>
    <table>
        <thead>
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>性别</th>
                <th>年龄</th>
                <th>班级</th>
            </tr>
        </thead>
        <tbody>
            <!-- 使用 JS 渲染 -->
        </tbody>
    </table>
    <script>
        /**
         *  需求:
         *      1. 接收到后端给到的数据
         *      2. 将数据渲染到页面
        */
        var users = [
            { id: 1, name: 'Jack', age: 18, gender: '男', classRoom: '2XX' },
            { id: 2, name: 'Rose', age: 20, gender: '女', classRoom: '2XX' },
            { id: 3, name: 'Jerry', age: 22, gender: '男', classRoom: '2XX' },
            { id: 4, name: 'Tom', age: 24, gender: '男', classRoom: '2XX' }
        ]

        var thBody = document.querySelectorAll('tbody')[0]
        console.log(thBody)//获取到需要操作的元素
        var str = users.reduce(function(prve,item) { //利用累加器将每次输出的结果储存
            return prve +
            `<tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.gender}</td>
                <td>${item.age}</td>
                <td>${item.classRoom}</td>
            </tr>`
        },'')
        thBody.innerHTML = str//innerHTML 可以渲染html结构
    </script>
</body>