简介

在 JavaScript 中,一个浏览器窗口就是一个 window 对象,简单地说,JavaScript 会把一个窗口看成一个对象,这样我们就可以用这个对象的属性和方法来操作这个窗口。实际上,我们在打开一个页面时,浏览器都会自动为这个页面创建一个 window 对象。

window 对象存放了这个页面的所有信息,为了更好地分类处理这些信息,window 对象下面又分为很多对象。image.png
image.png window 对象及下面这些 location、navigator 等子对象,由于都是用于操作浏览器窗口的,所以我们又称之为“BOM”,也就是 Browser Object Module(浏览器对象模型)。image.png

窗口操作

打开窗口

  1. window.open(url,target)

url 指的是新窗口的地址,如果 url 为空,则表示打开一个空白窗口。空白窗口很有用,我们可以使用 document.write( )往空白窗口输出文本,甚至输出一个 HTML 页面。

target 表示打开方式,它的取值跟 a 标签中 target 属性的取值是一样的,常用取值有两个:_blank 和 _self。当 target 为“_blank(默认值)”时,表示在新窗口中打开;当 target 为“_self”时,表示在当前窗口中打开。

  1. oBtn.onclick = function(){
  2. window.open("https://www.yuque.com/explore/events");
  3. window.open("https://www.yuque.com/explore/events","_blank");
  4. }
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <script>
  9. window.onload = function(){
  10. var oBtn = document.getElementById("btn");
  11. oBtn.onclick = function(){
  12. var opener = window.open();
  13. opener.document.write("a new page")
  14. opener.document.body.style.backgroundColor = "blue";
  15. }
  16. }
  17. </script>
  18. </head>
  19. <body>
  20. <input type="button" id="btn" value="button">
  21. </body>
  22. </html>
  1. window.open( )就像函数调用一样,会返回(也就是 return)一个值,这个值就是新窗口对应的 window 对象。

如果打开的是同一个域名下的页面或空白窗口,就可以像上面那样操作新窗口的元素或样式;但是如果打开的是另外一个域名下的页面,是不允许操作新窗口的内容的,因为涉及跨域的问题。

<!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.onload = function(){
      var oBtn = document.getElementById("btn");
      var opener = null;
      oBtn.onclick = function(){
        opener = window.open();
        var strHtml = '<!DOCTYPE html>\
<html lang="en">\
<head>\
  <title>Document</title>\
</head>\
<body>\
  <strong>someting</strong>\
</body>\
</html>';
opener.document.write(strHtml);
  }
}
  </script>
</head>
<body>
  <input type="button" id="btn" value="button">
</body>
</html>

关闭窗口

window.close()

对话框

alert

这个方法在之前用了很多次,这里不再多说。对于 alert( ),只需记住一点:在 alert( )中实现文本换行,用的是 \n。

confirm( )

提供文字,提供确认。

confirm("提示文字")

如果用户点击【确定】按钮,confirm( )会返回 true;如果用户点击【取消】按钮,则会返回 false。

<!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.onload = function () {
      var oBtn = document.getElementById("btn");
      oBtn.onclick = function () {
        if(confirm("are you sure?")){
          window.location.href = "https://weread.qq.com/web/reader/1fb32f0071cad7841fb22d7k65b326f026965b9eea6e6e1";
        }
      }
    }
  </script>
</head>

<body>
  <input type="button" id="btn">
</body>

</html>

prompt

prompt( )对话框不仅会提示文字,还会返回一个字符串。

prompt("提示文字")
<!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.onload = function () {
      var oBtn = document.getElementById("btn");
      oBtn.onclick = function () {
        var name = prompt("enter your name");
        document.write("welcome "+name);
    }
  }
  </script>
</head>

<body>
  <input type="button" id="btn">
</body>

</html>

image.png
一般不会采用默认的对话框,之后会进行学习。

定时器

实现网页计时,轮播图等,每隔一段事件就执行一次代码。

setTimeout( )和 clearTimeout( )

在 JavaScript 中,我们可以使用 setTimeout( )方法来“一次性”地调用函数,并且可以使用 clearTimeout( )来取消执行 setTimeout( )。

setTimeout(code,time)
参数 code 可以是一段代码,可以是一个函数,也可以是一个函数名。参数 time 是时间,单位为毫秒,表示要过多长时间才执行 code 中的代码。
<script>
    window.onload = function () {
      setTimeout('alert("欢迎")',2000)
  }
</script>

<script>
    window.onload = function () {
      setTimeout(function(){alert("欢迎")},2000)
  }
</script>

<script>
    window.onload = function () {
  //两种方式等价
      setTimeout(alertMes,2000)
      setTimeout("alertMes()",2000)
  }
    function alertMes(){
      alert("欢迎");
    }
</script>
<!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.onload = function () {
      var oBtn = document.getElementsByTagName("input");
      var timer = null;
      oBtn[0].onclick = function () {
        timer = setTimeout(
          function () { alert("welcome") }, 2000
        )
      }
      oBtn[1].onclick = function () {
        clearTimeout(timer)
      }
    }
  </script>
</head>

<body>
  <p>点击按钮,两秒后提示欢迎语句</p>
  <input type="button" value="开始">
  <input type="button" value="暂停">
</body>

</html>
如果点击【开始】按钮,2秒后就会弹出对话框。如果在 2 秒内再次点击【暂停】按钮,就不会弹出对话框。

setInterval( )和 clearInterval( )

在 JavaScript 中,我们可以使用 setInterval( )方法来“重复性”地调用函数,并且可以使用 clearInterval( )来取消执行 setInterval( )。

setInterval(code,time);
三种写法,同上。
<!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.onload = function () {
      var n = 5;
      setInterval(countDown,1000);
      function countDown(){
        if(n > 0){
          n--;
          document.getElementById("num").innerHTML = n;
        }
      }
    }
  </script>
</head>

<body>
  <div>倒计时:<span id="num">5</span></div>
</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 type="text/css">
    div{width: 100px;height: 100px;border: 1px solid silver;}
  </style>
  <script>
    window.onload = function(){
      var oBtn = document.getElementsByTagName("input");
      var oDiv = document.getElementsByTagName("div")[0];
      var colors = ["red","blue","orange","yellow","green","blue","purple"];
      var timer = null;
      var i = 0;
      oBtn[0].onclick = function(){
        timer = setInterval(
          function(){oDiv.style.backgroundColor = colors[i];i++;i%=colors.length},1000
        )
        oBtn[1].onclick = function(){
          clearInterval(timer);
        }
      }
    }
  </script>
</head>

<body>
  <input type="button" value="开始">
  <input type="button" value="暂停">
  <div></div>
</body>

</html>
其实每点击一次,都会新开一个 setInterval( ),如果你不断点击按钮, setInterval( )就会累加起来。也就是说,当你点击 3 次按钮时,其实已经开了 3 个 setInterval( ),此时如果想要停下来,就必须点击 3 次【暂停】按钮。为了避免产生这个累加的 bug,我们在每次点击【开始】按钮时就要清除一次定时器,改进后的代码如下。
<!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 type="text/css">
    div{width: 100px;height: 100px;border: 1px solid silver;}
  </style>
  <script>
    window.onload = function(){
      var oBtn = document.getElementsByTagName("input");
      var oDiv = document.getElementsByTagName("div")[0];
      var colors = ["red","blue","orange","yellow","green","blue","purple"];
      var timer = null;
      var i = 0;
      oBtn[0].onclick = function(){
        clearInterval(timer);
        timer = setInterval(
          function(){oDiv.style.backgroundColor = colors[i];i++;i%=colors.length},1000
        )
        oBtn[1].onclick = function(){
          clearInterval(timer);
        }
      }
    }
  </script>
</head>

<body>
  <input type="button" value="开始">
  <input type="button" value="暂停">
  <div></div>
</body>

</html>
优化:每一次点击开始之后就清除一次计时器。

location 对象

在 JavaScript 中,我们可以使用 window 对象下的 location 子对象来操作当前窗口的 URL。所谓的 URL,指的就是页面地址。对于 location 对象,我们只需要掌握以下 3 个属性:image.png

window.location.href

 <script>
    var url = window.location.href;
    document.write("URL: "+url);
</script>
<!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>
    setTimeout(function(){
      window.location.href = "https://www.bilibili.com/";
    },2000);
  </script>
</head>
<body>
  <p>两秒后跳转</p>
</body>
</html>

window.location.search

我们可以使用 location 对象的 search 属性来获取和设置当前页面地址“?”后面的内容。

<script>
    document.write(window.location.search);
</script>
此时页面是空白的,我们在浏览器地址后面加上 ?id=1(要自己手动输入),再刷新页面,就会出现结果了。

window.location.hash

我们可以使用 location 对象的 hash 属性来获取和设置当前页面地址井号(#)后面的内容。

<script>
    document.write(window.location.hash);
</script>

navigator 对象

我们可以使用 window 对象下的子对象 navigator 来获取浏览器的类型。

<script>
    document.write(window.navigator.userAgent);
</script>