BOM(browser object model)浏览器对象模型

window是浏览器的一个实例,在浏览器中,window对象有双重角色,它既是通过Javascript访问浏览器窗口的一个接口,又是ECMAScript规定的Global对象(全局对象)。

  1. var age =15;
  2. //声明一个全局变量
  3. window.name="chengchao";
  4. //相当于var name = "chengchao"

1 window对象的方法

1-1 alert

1-2 window.confirm( “msg”)

功能:显示一个带有指定消息和包含确定和取消按钮的对话框。点击确定返回true,取消返回false;

  1. var value = window.confirm("去不去")
  2. console.log(value) // true / false

1-3 window.prompt(“text”,”defaultText”)

  1. 参数说明
  2. text:在对话框中显示的文本
  3. defaultText:默认输入文本
  4. 返回值:点取消按钮,返回null
  5. 点确定按钮,返回输入的文本
  1. var temp = window.prompt("请输入","hello world")
  2. console.log(temp);

2 history 对象

  1. history对象保存了用户在浏览器中访问页面的历史记录
  2. 语法:history.back()
  3. 功能:回到历史记录的上一步
  4. 相当于是用了history.go(-1)
  5. //-1表示前一步,-2前两部
  6. 语法:history.go(1)
  7. 功能:回到历史记录的前一步
  8. 相当于history.forward()
  9. 语法:history.go(-n)
  10. 功能:回到历史记录的前n
  11. 语法:history.go(n)
  12. 功能:回到历史记录的后n

3 screen 对象

  1. screen对象包含有关客户端显示屏幕的信息
  2. screen.availWidth
  3. screen.availHeight
  4. // 获取屏幕的宽度
  5. var screenWidth = window.screen.availWidth;
  6. console.log(screenWidth);
  7. // 获取屏幕的可视区
  8. var viewWidth = document.body.clientWidth;
  9. console.log(viewWidth);

4 定时器

4-1 setTimeout 超时调用

特点:间歇一段时间,只会触发一次

  1. setTimeout(function(){
  2. console.log("hello");
  3. },2000)
  1. //使用递归 让超时调用实现间歇调用
  2. function show(){
  3. setTimeout(function(){
  4. console.log(1);
  5. show();
  6. },1000)
  7. }
  8. show()

4-2 setInterval 间歇调用

特点:每间隔一段时间就会触发

  1. setInterval(function(){
  2. console.log("world");
  3. },2000)

4-2-1 清除定时器

  1. <button id="btn">停止定时器</button>
  2. <script>
  3. var btn = document.getElementById("btn")
  4. var timer = setInterval(function(){
  5. console.log(2);
  6. },1000)
  7. btn.onclick = function(){
  8. clearInterval(timer)
  9. }
  10. </script>

5 navigator对象

  1. 1.掌握Navigator对象的userAgent属性
  2. 2.掌握如何判断浏览器的类型
  3. 3.掌握如何判断设备的终端是移动还是PC
  4. UserAgent:用来识别浏览器名称,版本,引擎以及操作系统等信息的内容。
  5. //检测浏览器类型
  6. if(/Android|iphone|webOS/i.test(navigator.userAgent)){
  7. location.href="mobile.html"
  8. }else if(/ipad/i.test(navigator.userAgent)){
  9. location.href="pad.html"
  10. }