---
# System prepended metadata

title: 串接API之DOM第一章
tags: [第一章, DOM, API]

---

---
tags: API,DOM,第一章
---
# 串接API之DOM第一章
# 基礎知識
JavaScript的組成
1.ECMAscript:JavaScript語法
2.DOM:頁面文檔對象模型
3.BOM:瀏覽器對象模型

Web APIs
1.是W3C組織的標準
2.學習DOM和BOM
3.JS獨有

API和WebAPI
1.API是提供一個接口，幫我們實現某種功能，不必糾結內部如何實現
2.WebAPI做瀏覽器交互效果
3.WebAPI有輸入和輸出，很多都是方法(函數)
4.WebAPI當成學內置對象
# DOM
Document Object Model
文檔對象模型
W3C推薦的處理可擴展標記語言(HTML或XML)
標準編程接口
![](https://i.imgur.com/OQnot6Z.jpg)
# 獲取頁面元素
1.根據ID
2.根據標籤名
3.根據HTML5新增方法
4.特殊元素
## document.getElementById
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementById
```
  <body>
    <div id="time">2100-1-1</div>
    <script>
      var timer = document.getElementById('time');
      console.log(timer); // 返回一个匹配到 ID 的 DOM Element 对象
      console.log(typeof timer);
      console.dir(timer); // 返回元素對象，只是更好查看裡面的屬性和方法
    </script>
  </body>
```
## document.getElementsByTagName
```html=
  <body>
    <ul>
      <li>天線寶寶說你好</li>
      <li>天線寶寶說你好</li>
      <li>天線寶寶說你好</li>
      <li>天線寶寶說你好</li>
      <li>天線寶寶說你好</li>
    </ul>
    <ol id="ol">
      <li>乒乒乓乓</li>
      <li>乒乒乓乓</li>
      <li>乒乒乓乓</li>
      <li>乒乒乓乓</li>
      <li>乒乒乓乓</li>
    </ol>
    <script>
      var lis = document.getElementsByTagName('li');
      console.log(lis); // 偽數組
      console.log(lis[0]);

      for (var i = 0; i < lis.length; i++) {
        console.log(lis[i]);
      }
      // 只有一個li還是返回偽數組
      // 沒有li返回空的偽數組

      //   var ol = document.getElementsByTagName('ol');
      //   console.log(ol[0].getElementsByTagName('li')); // 父元素必須是指定的單個元素

      var ol = document.getElementById('ol');
      console.log(ol.getElementsByTagName('li'));
    </script>
  </body>
```
## querySelector
H5新增方法
```html=
  <body>
    <div class="box">盒子1</div>
    <div class="box">盒子2</div>
    <div id="nav">
      <ul>
        <li>首頁</li>
        <li>產品</li>
      </ul>
    </div>
    <script>
      // 根據類名獲得某些元素集合
      var boxs = document.getElementsByClassName('box');
      console.log(boxs);
      // 返回指定選擇器的第一個元素對象
      var firstBox = document.querySelector('.box');
      console.log(firstBox);
      var nav = document.querySelector('#nav');
      console.log(nav);
      var li = document.querySelector('li');
      console.log(li);
      // 返回指定選擇器的所有元素對象
      var allBox = document.querySelectorAll('.box');
      console.log(allBox);
    </script>
  </body>
```
## 獲取body獲取html
```
  <body>
    <script>
      // 獲取body
      var bodyEle = document.body;
      console.log(bodyEle);
      console.dir(bodyEle);
      // 獲取html
      var htmlEle = document.html;
      console.log(htmlEle); // 不行
      var htmlEle = document.documentElement;
      console.log(htmlEle);
    </script>
  </body>
```
# 事件
事件三要素
1.事件源
事件觸發對象
EX:按鈕
2.事件類型
如何觸發
EX:滑鼠點擊、滑鼠經過、鍵盤按下
3.事件處理程序
利用函數賦值
```
  <body>
    <button id="btn">唐伯虎</button>
    <script>
      var btn = document.getElementById('btn');
      btn.onclick = function () {
        alert('點秋香');
      };
    </script>
  </body>
```


| 鼠標事件    | 觸發條件         |
| ----------- | ---------------- |
| onclick     | 滑鼠點擊左鍵觸發 |
| onmouseover | 滑鼠經過觸發     |
| onmouseout  | 滑鼠離開觸發     |
| onfocus     | 獲得滑鼠焦點觸發 |
| onblur      | 失去滑鼠焦點觸發 |
| onmousemove | 滑鼠移動觸發     |
| onmouseup   | 滑鼠彈起觸發     |
| onmousedown | 滑鼠按下觸發     |
## 操作元素
```
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 300px;
        height: 30px;
        line-height: 30px;
        color: #fff;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <button>顯示系統時間</button>
    <div>某個時間</div>
    <p>123</p>
    <script>
      // 1.獲取元素
      var btn = document.querySelector('button');
      var div = document.querySelector('div');
      // 2.註冊事件
      btn.onclick = function () {
        div.innerText = getDate();
      };
      function getDate() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var dates = date.getDate();
        var arr = [
          '星期日',
          '星期一',
          '星期二',
          '星期三',
          '星期四',
          '星期五',
          '星期六'
        ];
        var day = date.getDay();
        return (
          '今天是:' + year + '年' + month + '月' + dates + '日 ' + arr[day]
        );
      }
      var p = document.querySelector('p');
      p.innerText = getDate();
    </script>
  </body>
```
## innerText innerHTML
```
  <body>
    <div></div>
    <p>
      安安你好
      <span>123</span>
    </p>
    <script>
      // 1.innerText 不識別html標籤 非標準
      var div = document.querySelector('div');
      div.innerText = '<strong>今天是</strong>晴天';
      // 2.innerHTML 識別html標籤 W3C標準 保留空格和換行
      div.innerHTML = '<strong>今天是</strong>晴天';
      var p = document.querySelector('p');
      console.log(p.innerText);
      console.log(p.innerHTML);
    </script>
  </body>
```
## 修改元素屬性
1 innerText innerHTML
2 src href
3 id alt title
```
  <body>
    <button id="komame">茸茸鼠</button>
    <button id="stanley">史丹利</button>
    <br>
    <img src="komame.jpg" alt="" title="茸茸鼠" />
    <script>
      var mouse = document.getElementById('komame');
      var fat = document.getElementById('stanley');
      var img = document.querySelector('img');
      fat.onclick = function () {
        img.src = 'stanley.jpg';
        img.title = '史丹利';
      };
      mouse.onclick = function () {
        img.src = 'komame.jpg';
        img.title = '茸茸鼠';
      };
    </script>
  </body>
```
## 分時問候案例
```
  <body>
    <img src="sun.jpg" alt="" />
    <div>早安</div>
    <script>
      // 1.獲取元素
      var img = document.querySelector('img');
      var div = document.querySelector('div');
      // 2.獲取時間
      var date = new Date();
      var h = date.getHours();
      // 3.判斷時間
      if (h < 12) {
        img.src = 'sun.jpg';
        div.innerHTML = '早安';
      } else if (h < 18) {
        img.src = 'sunset.jpg';
        div.innerHTML = '午安';
      } else {
        img.src = 'moon.jpg';
        div.innerHTML = '晚安';
      }
    </script>
  </body>
```
## 操作表單
type
value
ckecked
selected
disabled
```
  <body>
    <button>按鈕</button>
    <input type="text" value="輸入內容" />
    <script>
      var btn = document.querySelector('button');
      var input = document.querySelector('input');
      btn.onclick = function () {
        // input.innerHTML = '點擊了'; // 不能這樣寫
        input.value = '被點擊了';
        // btn.disabled = true;
        this.disabled = true;
      };
    </script>
  </body>
```
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        position: relative;
        width: 400px;
        border-bottom: 1px solid #ccc;
        margin: 100px auto;
      }
      .box input {
        width: 370px;
        height: 30px;
        border: 0;
        outline: none;
      }
      .box img {
        position: absolute;
        top: 2px;
        right: 2px;
        width: 24px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <label for="">
        <img src="close.jpg" alt="" id="eye" />
      </label>
      <input type="password" name="" id="pwd" />
    </div>
    <script>
      var eye = document.getElementById('eye');
      var pwd = document.getElementById('pwd');
      var flag = 0;
      eye.onclick = function () {
        if (flag == 0) {
          pwd.type = 'text';
          eye.src = 'open.jpg';
          flag = 1;
        } else {
          pwd.type = 'password';
          eye.src = 'close.jpg';
          flag = 0;
        }
      };
    </script>
  </body>
</html>
```
## 修改樣式
通過JS修改元素大小、顏色、位置
element.style    行內樣式操作
element.className    類名樣式操作
注意
駝峰命名:fontSize、backgroundColor
產生行內式:css權重高
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 200px;
        height: 200px;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <div></div>
    <script>
      var div = document.querySelector('div');
      div.onclick = function () {
        this.style.backgroundColor = 'purple';
        this.style.width = '250px';
      };
    </script>
  </body>
</html>
```
## 淘寶二維碼
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        position: relative;
        width: 74px;
        height: 88px;
        border: 1px solid #ccc;
        margin: 100px auto;
        font-size: 12px;
        text-align: center;
        color: #f40;
        /* display: block; */
      }
      .box img {
        width: 60px;
        margin-top: 5px;
      }
      .close-btn {
        position: absolute;
        top: -1px;
        left: -16px;
        width: 14px;
        height: 14px;
        border: 1px solid #ccc;
        line-height: 14px;
        font-family: Arial, Helvetica, sans-serif;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div class="box">
      淘寶二維碼
      <img src="tao.jpg" alt="" />
      <i class="close-btn">x</i>
    </div>
    <script>
      var btn = document.querySelector('.close-btn');
      var box = document.querySelector('.box');
      btn.onclick = function () {
        box.style.display = 'none';
      };
    </script>
  </body>
</html>
```
## 輪播精靈圖
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      li {
        list-style-type: none;
      }
      .box {
        width: 250px;
        margin: 100px auto;
      }
      .box li {
        float: left;
        width: 24px;
        height: 24px;
        background-color: pink;
        margin: 15px;
        background: url(elf.jpg) no-repeat;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </div>
    <script>
      var lis = document.querySelectorAll('li');
      for (var i = 0; i < lis.length; i++) {
        var index = i * 48;
        lis[i].style.backgroundPosition = '0-' + index + 'px';
      }
    </script>
  </body>
</html>
```
## 顯示隱藏文本框
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      input {
        color: #999;
      }
    </style>
  </head>
  <body>
    <input type="text" value="手機" />
    <script>
      var text = document.querySelector('input');
      text.onfocus = function () {
        console.log('得到了焦點');
        if (this.value === '手機') {
          this.value = '';
        }
        this.style.color = '#333';
      };
      text.onblur = function () {
        console.log('失去了焦點');
        if (this.value === '') {
          this.value = '手機';
          this.style.color = '#999';
        }
      };
    </script>
  </body>
</html>
```
## className
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 100px;
        height: 100px;
        background-color: pink;
      }
      .change {
        background-color: purple;
        color: #fff;
        font-size: 25px;
        margin-top: 100px;
      }
    </style>
  </head>
  <body>
    <div class="first">文本</div>
    <script>
      var test = document.querySelector('div');
      test.onclick = function () {
        // this.style.backgroundColor = 'purple';
        // this.style.color = '#fff';
        // this.style.fontSize = '25px';
        // this.style.marginTop = '100px';
        // this.className = 'change'; // 原本的會被覆蓋
        this.className = 'first change';
      };
    </script>
  </body>
</html>
```
## 密碼框驗證訊息
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 600px;
        margin: 100px auto;
      }
      .message {
        display: inline-block;
        font-size: 12px;
        color: #999;
        background: url(mess.jpg) no-repeat left center;
        padding-left: 20px;
      }
      .wrong {
        color: red;
        background-image: url(wrong.jpg);
      }
      .right {
        color: green;
        background-image: url(right.jpg);
      }
    </style>
  </head>
  <body>
    <div class="register">
      <input type="password" class="ipt" />
      <p class="message">請輸入6~16位密碼</p>
    </div>
    <script>
      var ipt = document.querySelector('.ipt');
      var message = document.querySelector('.message');
      ipt.onblur = function () {
        if (this.value.length < 6 || this.value.length > 16) {
          console.log('錯誤');
          message.className = 'message wrong';
          message.innerHTML = '你輸入的位數不是6~16位';
        } else {
          message.className = 'message right';
          message.innerHTML = '輸入正確';
        }
      };
    </script>
  </body>
</html>
```
## 排他思想
注意
for循環的i
有全局變量與局部變量
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>按鈕1</button>
    <button>按鈕2</button>
    <button>按鈕3</button>
    <button>按鈕4</button>
    <button>按鈕5</button>
    <script>
      var btns = document.getElementsByTagName('button');
      // btns得到的是偽數組  裡面每個元素btns[i]
      for (var i = 0; i < btns.length; i++) {
        btns[i].onclick = function () {
          for (var i = 0; i < btns.length; i++) {
            btns[i].style.backgroundColor = '';
          }
          this.style.backgroundColor = 'pink';
        };
      }
    </script>
  </body>
</html>
```
## 網頁換膚
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        background: url(bg1.jpg) no-repeat center top;
      }
      li {
        list-style: none;
      }
      .baidu {
        overflow: hidden;
        margin: 100px auto;
        background-color: #fff;
        width: 410px;
        padding-top: 3px;
      }
      .baidu li {
        float: left;
        margin: 0 1px;
        cursor: pointer;
      }
      .baidu img {
        width: 100px;
      }
    </style>
  </head>
  <body>
    <ul class="baidu">
      <li><img src="bg1.jpg" /></li>
      <li><img src="bg2.jpg" /></li>
      <li><img src="bg3.jpg" /></li>
      <li><img src="bg4.jpg" /></li>
    </ul>
    <script>
      var imgs = document.querySelector('.baidu').querySelectorAll('img');
      for (var i = 0; i < imgs.length; i++) {
        imgs[i].onclick = function () {
          document.body.style.backgroundImage = 'url(' + this.src + ')';
        };
      }
    </script>
  </body>
</html>
```
## 隔行變色
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      thead tr {
        height: 30px;
        background-color: skyblue;
      }
      tbody tr {
        height: 30px;
      }
      tbody td {
        border-bottom: 1px solid #d7d7d7;
        font-size: 12px;
        color: blue;
      }
      .bg {
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th>代碼</th>
          <th>名稱</th>
          <th>最新公布淨值</th>
          <th>累計淨值</th>
          <th>前單位淨值</th>
          <th>淨值增長率</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>003526</td>
          <td>定期開放債卷</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>定期開放債卷</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>定期開放債卷</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>定期開放債卷</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>定期開放債卷</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>定期開放債卷</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
      </tbody>
    </table>
    <script>
      var trs = document.querySelector('tbody').querySelectorAll('tr');
      for (var i = 0; i < trs.length; i++) {
        trs[i].onmouseover = function () {
          this.className = 'bg';
        };
        trs[i].onmouseout = function () {
          this.className = '';
        };
      }
    </script>
  </body>
</html>
```
## 表單全選取消全選
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="wrap">
      <table>
        <thead>
          <tr>
            <th>
              <input type="checkbox" id="j_cbAll" />
            </th>
            <th>商品</th>
            <th>價錢</th>
          </tr>
        </thead>
        <tbody id="j_tb">
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>iphone</td>
            <td>8000</td>
          </tr>
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>iphone</td>
            <td>8000</td>
          </tr>
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>iphone</td>
            <td>8000</td>
          </tr>
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>iphone</td>
            <td>8000</td>
          </tr>
        </tbody>
      </table>
    </div>
    <script>
      var j_cbAll = document.getElementById('j_cbAll');
      var j_tbs = document.getElementById('j_tb').getElementsByTagName('input');
      j_cbAll.onclick = function () {
        console.log(this.checked);
        for (var i = 0; i < j_tbs.length; i++) {
          j_tbs[i].checked = this.checked;
        }
      };
      for (var i = 0; i < j_tbs.length; i++) {
        j_tbs[i].onclick = function () {
          var flag = true;
          for (var i = 0; i < j_tbs.length; i++) {
            if (!j_tbs[i].checked) {
              flag = false;
              break; // 提高執行效率
            }
          }
          j_cbAll.checked = flag;
        };
      }
    </script>
  </body>
</html>
```