---
# System prepended metadata

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

---

---
tags: API,BOM,第一章
---
# 串接API之BOM第一章
# 基礎知識
BOM(Browser Object Model)瀏覽器對象模型
與瀏覽器窗口進行交互的對象
核心對象是window
BOM由一系列相關對象構成
BOM缺乏標準
DOM標準組織為W3C
JavaScript標準組織為ECMA
![](https://i.imgur.com/5MNiGH0.jpg)
window對象是瀏覽器頂級對象
1.JS訪問瀏覽器窗口的一個接口
2.全局作用域的變量與函數都會變成window的屬性與方法
3.調用時都可以省略window
```
  <body>
    <script>
      console.dir(window);
      console.log(window.name);
    </script>
  </body>
```
## 頁面加載事件
window.onload = function(){}
window.addEventListener('load',function(){});
文檔內容完全加載完就會觸發該事件
## 頁面加載事件進階
document.addEventListener('DOMContentLoaded',function(){})
DOM加載完就觸發該事件，不加載圖片、樣式表、flash等等
```
<!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>
    <script>
      window.addEventListener('load', function () {
        var btn = document.querySelector('button');
        btn.addEventListener('click', function () {
          alert('點擊我');
        });
      });
      window.addEventListener('load', function () {
        alert(22);
      });
      document.addEventListener('DOMContentLoaded', function () {
        alert(33);
      });
    </script>
  </head>
  <body>
    <button>點擊我</button>
  </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 {
        height: 200px;
        width: 200px;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <div></div>
    <script>
      var div = document.querySelector('div');
      window.addEventListener('resize', function () {
        console.log(window.innerWidth);
        console.log('變化了');
        if (window.innerWidth <= 800) {
          div.style.display = 'none';
        } else {
          div.style.display = 'block';
        }
      });
    </script>
  </body>
</html>
```
## 定時器
window.setTimeout(調用函數,延遲的毫秒數);
window可以省略
1000毫秒=1秒
毫秒數省略默認是0
```
  <body>
    <script>
      setTimeout(function () {
        console.log('時間到了');
      }, 2000);
      function callback() {
        console.log('爆炸了');
      }
      var timer1 = setTimeout(callback, 3000); // 寫法1
      var timer2 = setTimeout('callback()', 5000); // 寫法2不建議
    </script>
  </body>
```
範例
```
  <body>
    <img src="komame.jpg" alt="" class="ad" />
    <script>
      var ad = document.querySelector('.ad');
      setTimeout(function () {
        ad.style.display = 'none';
      }, 5000);
    </script>
  </body>
```
## 回調函數
window.setTimeout(調用函數,延遲的毫秒數);
element.onclick=function(){}
element.addEventListener('click',fn);
以上都是回調函數
## 停止定時器
window.clearTimeout(timeoutID);
```
  <body>
    <button>點擊停止定時器</button>
    <script>
      var btn = document.querySelector('button');
      var timer = setTimeout(function () {
        console.log('爆炸了');
      }, 5000);
      btn.addEventListener('click', function () {
        clearTimeout(timer);
      });
    </script>
  </body>
```
## 重複定時器
window.setInterval(調用函數,延遲的毫秒數);
```
  <body>
    <script>
      setInterval(function () {
        console.log('繼續輸出');
      }, 1000);
    </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>
      span {
        display: inline-block;
        width: 200px;
        height: 200px;
        background-color: white;
      }
    </style>
  </head>
  <body>
    <div>
      <span class="hour">1</span>
      <span class="minute">2</span>
      <span class="second">3</span>
    </div>
    <script>
      var hour = document.querySelector('.hour');
      var minute = document.querySelector('.minute');
      var second = document.querySelector('.second');
      var inputTime = +new Date('2100-1-1 00:00:00'); // 用戶輸入的時間總毫秒數
      countDown();
      setInterval(countDown, 1000);
      function countDown(time) {
        var nowTime = +new Date(); // 當前的時間總毫秒數
        var times = (inputTime - nowTime) / 1000; // 剩餘時間總毫秒數  轉成秒數
        var h = parseInt((times / 60 / 60) % 24);
        h = h < 10 ? '0' + h : h;
        hour.innerHTML = h;
        var m = parseInt((times / 60) % 60);
        m = m < 10 ? '0' + m : m;
        minute.innerHTML = m;
        var s = parseInt(times % 60);
        s = s < 10 ? '0' + s : s;
        second.innerHTML = s;
      }
    </script>
  </body>
</html>
```
## 停止重複定時器
window.clearInterval(IntervalID);
```
  <body>
    <button class="begin">開啟</button>
    <button class="stop">停止</button>
    <script>
      var begin = document.querySelector('.begin');
      var stop = document.querySelector('.stop');
      var timer = null;
      begin.addEventListener('click', function () {
        timer = setInterval(function () {
          console.log('你好嗎');
        }, 1000);
      });
      stop.addEventListener('click', function () {
        clearInterval(timer);
      });
    </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>
  </head>
  <body>
    手機號碼: <input type="number" /><button>發送</button>
    <script>
      var btn = document.querySelector('button');
      var time = 3;
      btn.addEventListener('click', function () {
        btn.disabled = true;
        function first() {
          btn.innerHTML = '還剩下' + time + '秒';
          time--;
          console.log(1);
        }
        first();
        var timer = setInterval(function () {
          if (time == 0) {
            clearInterval(timer);
            btn.disabled = false;
            btn.innerHTML = '發送';
            time = 3;
          } else {
            btn.innerHTML = '還剩下' + time + '秒';
            time--;
            console.log(2);
          }
        }, 1000);
      });
    </script>
  </body>
</html>
```
## this指向問題
```
<!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>123</button>
    <script>
      // 1.全局作用域和普通函數
      console.log(this);
      function fn() {
        console.log(this);
      }
      window.fn();
      window.setTimeout(function () {
        console.log(this);
      }, 1000);
      // 2.方法調用
      var o = {
        sayHi: function () {
          console.log(this);
        }
      };
      o.sayHi();
      var btn = document.querySelector('button');
      btn.onclick = function () {
        console.log(this);
      };
      btn.addEventListener('click', function () {
        console.log(this);
      });
      // 3.構造函數
      function Fun() {
        console.log(this);
      }
      var fun = new Fun();
    </script>
  </body>
</html>
```
## 異步與同步
JavaScript是單線程，同一時間只能做一件事
```
    <script>
      // 問題一
      console.log(1);
      setTimeout(function () {
        console.log(3);
      }, 1000);
      console.log(2);
    </script>
```
```
    <script>
      // 問題二
      console.log(1);
      setTimeout(function () {
        console.log(3);
      }, 0);
      console.log(2);
    </script>
```
同步任務
都在主線程上執行，形成一個執行棧
異步任務
放在任務隊列
由回調函數實現
有三種類型
1.普通事件，click、resize
2.資源加載，load、error
3.定時器，setTimeout、setInterval
![](https://i.imgur.com/hXQQcpm.jpg)
## location對象
重點記住:href和search
![](https://i.imgur.com/TuFy1Xl.jpg)
![](https://i.imgur.com/uDli6aH.jpg)
## 5秒鐘跳轉頁面
```
<!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>點擊</button>
    <div></div>
    <script>
      var btn = document.querySelector('button');
      var div = document.querySelector('div');
      btn.addEventListener('click', function () {
        location.href = 'https://www.google.com';
      });
      var timer = 5;
      function first() {
        div.innerHTML = '你將在' + timer + '秒鐘之後跳轉到首頁';
        timer--;
      }
      first();
      setInterval(function () {
        if (timer == 0) {
          location.href = 'https://www.google.com';
        } else {
          div.innerHTML = '你將在' + timer + '秒鐘之後跳轉到首頁';
          timer--;
        }
      }, 1000);
    </script>
  </body>
</html>
```
## 獲取URL
頁面一
```
<!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>
    <form action="index.html">
      用戶名: <input type="text" name="uname" />
      <input type="submit" value="登錄" />
    </form>
  </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></div>
    <script>
      console.log(location.search); // ?uname=123
      // substr('起始的位置',截取幾個字符[不寫就是截到完])
      var params = location.search.substr(1); // uname=123
      console.log(params);
      // 把字符串分割為數組split('=')
      var arr = params.split('=');
      console.log(arr);
      var div = document.querySelector('div');
      div.innerHTML = arr[1] + '歡迎您';
    </script>
  </body>
</html>
```
## location常見方法
![](https://i.imgur.com/BMTZniZ.jpg)
```
<!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>點擊</button>
    <script>
      var btn = document.querySelector('button');
      btn.addEventListener('click', function () {
        // 記錄歷史，可以後退
        // location.assign('https://www.google.com');
        // 不記錄歷史，不可以後退
        // location.replace('https://www.google.com');
        // 刷新頁面
        // location.reload();
        // 強制刷新頁面
        // location.reload(true);
      });
    </script>
  </body>
</html>
```
## navigator對象
![](https://i.imgur.com/07BsiH3.jpg)
## history對象
history.forward();
history.back();
history.go(數字);
數字1前進1步
數字2前進2步
數字-1後退1步
數字-2後退2步
頁面一
```
<!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>
    <a href="p96-1.html">點我前往列表頁</a>
    <button>前進</button>
    <script>
      var btn = document.querySelector('button');
      btn.addEventListener('click', function () {
        // history.forward();
        history.go(1);
      });
    </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>
    <a href="p96.html">點我前往首頁</a>
    <button>後退</button>
    <script>
      var btn = document.querySelector('button');
      btn.addEventListener('click', function () {
        // history.back();
        history.go(-1);
      });
    </script>
  </body>
</html>
```

