天天看点

JavaScript(7)-BOM一、BOM简介二、window 对象的主要属性三、window 对象的主要方法四、window 对象的主要子对象五、计时事件

一、BOM简介

BOM(Browser Object Model)即浏览器对象模型,它提供了独立于内容而与浏览器窗口进行交互的对象,其核心对象是 window。

Window 对象

window对象是浏览器的顶级对象。表示浏览器中打开的窗口。

window对象是一个全局对象。定义在全局作用域中的变量、函数都自动成为 window 对象的属性和方法。

  • window 对象中的主要属性:确定浏览器窗口的尺寸
  • window 对象中的主要方法:
    1. 打开/关闭窗口的控制方法
    2. 各种操作弹框
  • window 对象中的主要子对象:
    1. Screen屏幕
    2. Location获得当前页面的url地址
    3. History历史
    4. Navigator浏览器信息

二、window 对象的主要属性

确定浏览器窗口尺寸

浏览器的视口,不包括工具栏和滚动条。

有三种方法能够确定浏览器窗口的尺寸:

方法一

对于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:

window.innerWidth - 浏览器窗口的内部宽度

window.innerHeight - 浏览器窗口的内部高度

var w = window.innerWidth;  // 浏览器窗口的内部宽度
var h = window.innerHeight; // 浏览器窗口的内部高度
var h2 = document.querySelector('h2');
h2.innerHTML = 'window.innerWidth:' + w + '<br>' + 'window.innerHeight:' + h;
           

方法二

对于 Internet Explorer 5/6/7/8:(client:客户)

document.documentElement.clientWidth

document.documentElement.clientHeight

var w_2 = document.documentElement.clientWidth;
var h_2 = document.documentElement.clientHeight;
var new2 = document.createElement('h4'); // 创建元素节点 h4
new2.innerHTML = 'document.documentElement.clientWidth:' + w_2 + '<br>' + 'document.documentElement.clientHeight:' + h_2;  // 给创建的节点h4赋值
h2.appendChild(new2);  // 父级h2上面已经获取过了 在父节点h2的末尾追加h4
           

方法三

对上面的简写 获得的是body的宽高(没有给宽高时由内容撑开)

document.body.clientWidth

document.body.clientHeight

var w_3 = document.body.clientWidth;
var h_3 = document.body.clientHeight;
var h3 = document.querySelector('h3');
h3.innerHTML = 'document.body.clientWidth:' + w_3 + '<br>' + 'document.body.clientHeight:' + h_3;
           

三、window 对象的主要方法

1. 打开窗口 window.open()

window.open(URL,name,features,replace)
  • URL:一个可选的字符串,声明了要在新窗口中显示的文档的 URL
  • name:一个可选的字符串,该字符声明了新窗口的名称,这个名称可以用作标记 a 和 form 的属性 target 的值。
  • features:一个可选的字符串,声明了新窗口要显示的标准浏览器的特征
  • replace:一个可选的布尔值。true - URL 替换浏览历史中的当前条目。false - URL 在浏览历史中创建新的条目。
<button onclick="opentest1();">打开新的窗口</button>
function opentest1() {
  // window.open('01-test.html', 'test1', 'width=500,height=500', false);
  window.open('01-test.html');  // 后三个参数可选 一般写新页面的url参数即可
  // window.open('http://www.baidu.com/');
}
           

2. 关闭窗口 window.close()

window.close() 方法用于关闭浏览器窗口。无参数
<button onclick="closethis();">关闭当前窗口</button>
function closethis() {
  window.close();
}
           

3. 警告框 alert()

警告框经常用于确保用户可以得到某些信息。

当警告框出现后,用户需要点击确定按钮才能继续进行操作。

语法:window.alert(“sometext”);

可以不带上window对象,直接使用 alert() 方法

<button onclick="testalert();">alert警告框</button>
<script>
  function testalert() {
    alert('测试警告框');
  }
</script>
           

4. 确认框 confirm()

确认框通常用于验证是否接受用户操作。

当确认卡弹出时,用户可以点击 “确认” 或者 “取消” 来确定用户操作。

当你点击 “确认”, 确认框返回 true, 如果点击 “取消”, 确认框返回 false。

语法:window.confirm(“sometext”);

可以不带上window对象,直接使用 confirm() 方法

<button onclick="testconfirm();">confirm确认框</button>
<script>
function testconfirm() {
  var flag = window.confirm('确认要关闭吗?');  // 当点击确认/取消时,会返回t/f
  if (flag) {   // 当返回值为true时,即客户点击了确认,则关闭当前页面
    window.close();
  }
}
</script>
           

5. 提示框

提示框经常用于提示用户在进入页面前输入某个值。

当提示框出现后,用户需要输入某个值,然后点击确认或取消按钮才能继续操纵。

如果用户点击确认,那么返回值为输入的值。如果用户点击取消,那么返回值为 null。

语法:window.prompt(“sometext”,“defaultvalue”);

可以不带上window对象,直接使用 prompt() 方法

<button onclick="testprompt()">prompt提示框</button>
<script>
function testprompt() {
  var msg = window.prompt('请输入姓名:', 'admin');  // admin为默认值
  if (msg != null && msg != 'admin') {  // 当输入值不为空,且不是默认值时,在弹出框中显示出用户输入的值
    window.alert('您的姓名是:' + msg);
  }
}
</script>
           

练习案例:猜数字游戏

<button onclick="play()">开始猜数字游戏</button>
<script>
  function play() {
    var num = parseInt(Math.random() * 100 + 1);  // 获得一个随机整数
    do {
      var num1 = prompt('请输入1~100之间的一个整数');
      if (num1 < num) {
        alert('猜小了');
      } else if (num1 > num) {
        alert('猜大了');
      } else {
        alert('恭喜您,猜对了!');
      }
    } while (num1 != num);
  }
</script>
           

四、window 对象的主要子对象

1. Screen 屏幕

window.screen 对象包含有关用户屏幕的信息。

在编写时可以不使用 window 这个前缀。

有以下属性:

1)总宽度和总高度 screen.width / screen.height

是整个屏幕的宽和高,区别与浏览器视口宽高,屏幕大小尺寸不会随着浏览器窗口调整大小而变化。

<p id="p1"></p>
<script>
  var p1 = document.getElementById('p1');
  var totlew = window.screen.width;
  var totleh = window.screen.height;
  p1.innerHTML = '总宽度screen.width为:' + totlew + ' , ' + '总高度screen.height为:' + totleh;
</script>
           

2)可用宽度和可用高度 screen.availWidth / screen.availHeight

可用宽度 / 高度不包括分配给半永久特性(如屏幕底部的任务栏)的垂直空间。

<p id="p2"></p>
<script>
  var p2 = document.getElementById('p2');
  var availw = window.screen.availWidth;
  var availh = window.screen.availHeight;
  p2.innerHTML = '可用宽度screen.availWidth为:' + availw + ' , ' + '可用高度screen.availHeight为:' + availh;
</script>
           

3)色彩深度 screen.colorDepth

colorDepth 属性返回目标设备或缓冲器上的调色板的比特深度。

<p id="p3"></p>
<script>
  var p3 = document.getElementById('p3');
  var colorDepth = window.screen.colorDepth;
  p3.innerHTML = '色彩深度screen.colorDepth为:' + colorDepth;
</script>
           

4)色彩分辨率 screen.pixelDepth

pixelDepth 属性返回显示屏幕的颜色分辨率(比特每像素)。

<p id="p4"></p>
<script>
  var p4 = document.getElementById('p4');
  var pixelDepth = window.screen.pixelDepth;
  p4.innerHTML = '色彩分辨率screen.pixelDepth为:' + pixelDepth;
</script>
           

2. Location 获得当前页面的url地址

window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。

window.location 对象在编写时可不使用 window 这个前缀。

URL

统一资源定位符(Uniform Resource Locator)是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。

window.location 对象的2个属性:

1)location.href

location.href 属性返回当前页面的 URL。

<button onclick="testHref();">点击查询当前页面的URL</button>
<script>
  function testHref() {
    var url1 = window.location.href;
    var flag = confirm('当前页面的URL地址为:' + url1 + '\n' + '是否要跳转至新页面?')
    if (flag) {
      window.location.href = 'success.html';
    }
  }
</script>
           

2)location.search

location.search 属性是一个可读可写的字符串,可设置或返回当前 URL 的查询部分(问号 ? 之后的部分)。

<input type="text" id="uname">
<input type="password" id="psd">
<button onclick="login();">登录</button>
<script>
  function login() {
    var unamobj = document.getElementById('uname');  // 得到用户名文本框
    var uname = unamobj.value;  // 得到用户名文本框里的值
    var psdobj = document.getElementById('psd');  // 得到密码框
    var psd = psdobj.value;  // 得到密码框里的值
    // 当用户名和密码为给定的值时,携带该值跳转到success页面
    if (uname == 'zhangsan' && psd == '123456') {
      window.location.href = 'success.html?uname=' + uname + '&psd=' + psd;
    } else {  // 否则提示错误,并清空用户名和密码输入框
      window.alert('用户名密码输入有误,请重新输入!');
      unamobj.value = '';
      psdobj.value = '';
    }
  }
</script>
           

在登录成功的页面显示用户名:

<h1></h1>
<script>
  window.onload = function () {
    // location.search问号?之后的部分(包含?问号) 
    var query = window.location.search;
    // console.log(query); // ?uname=zhangsan&psd=123456
    var infoArray = query.split('&'); // split把字符串分割为字符串数组
    // console.log(infoArray);  // ['?uname=zhangsan', 'psd=123456']
    var uname = '';
    var psd = '';
    for (var k in infoArray) {
      var info = infoArray[k];  // for in 循环拿到的是下标 用索引号拿到字符串对象
      var msgArray = info.split('=');  // 用=号把键值对割开
      if (msgArray[0] == '?uname') {
        uname = msgArray[1];
      }
      if (msgArray[0] == 'psd') {
        psd = msgArray[1];
      }
    }
    // 得到h1对象 并向h1里面写入内容
    var h1 = document.querySelector('h1');
    h1.innerHTML = uname + ',登陆成功!您输入的密码是:' + psd;
  }
</script>
           

3. History 历史

window.history 对象包含浏览器的URL历史。

在编写时可不使用 window 这个前缀。

方法:

1)history.back()

history.back() 方法加载历史列表中的前一个 URL。这与在浏览器中点击后退按钮是相同的

2)history forward()

history forward() 方法加载历史列表中的下一个 URL。这与在浏览器中点击前进按钮是相同的

第一个页面:
<h1>071-test.html</h1>
<a href="072-test.html">跳转至下一页</a>
<button onclick="testforward();">==></button>
<script>
  function testforward() {
    window.history.forward();
  }
</script>
           
中间页面:
<a href="071-test.html">跳转至上一页</a>
<button onclick="testback();">上一页</button>
<script>
  function testback() {
    window.history.back();
  }
</script>

<a href="073-test.html">跳转至下一页</a>
<button onclick="testforward();">下一页</button>
<script>
  function testforward() {
    window.history.forward();
  }
</script>
           
最后一个页面:
<h1>073-test.html</h1>
<button onclick="testback();">&lt;== </button>
<script>
  function testback() {
    window.history.back();
  }
</script>
           

4. Navigator 浏览器信息

document.write("<h1>浏览器代号:" + window.navigator.appCodeName + "</h1>");
document.write("<h1>浏览器名称:" + window.navigator.appName + "</h1>");
document.write("<h1>浏览器版本:" + window.navigator.appVersion + "</h1>");
document.write("<h1>启用Cookies:" + window.navigator.cookieEnabled + "</h1>");
document.write("<h1>硬件平台:" + window.navigator.platform + "</h1>");
document.write("<h1>用户代理:" + window.navigator.userAgent + "</h1>");
document.write("<h1>用户代理语言:" + window.navigator.systemLanguage + "</h1>");
           

五、计时事件

window 对象给我们提供了 2 个非常好用的方法——定时器。

  • setTimeout()
  • setInterval()

1. setInterval()

间隔指定的毫秒数不停地执行指定的代码

语法:setInterval(“javascript function”,milliseconds);
  • 参数1 —— 函数(function)
  • 参数2 —— 间隔的毫秒数(1000 毫秒是一秒)

clearInterval()

用于停止 setInterval() 方法执行的函数代码

语法:clearInterval(intervalVariable)
  • intervalVariable参数 是 setInterval() 的返回值
<h1 id="time"></h1>
<button onclick="stop();">停止计时</button>
<script>
// 创建事件日期对象
function getDate() {
  var date1 = new Date();
  var y = date1.getFullYear();
  var m = date1.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  var d = date1.getDate();
  d = d < 10 ? '0' + d : d;
  var h = date1.getHours();
  h = h < 10 ? '0' + h : h;
  var min = date1.getMinutes();
  min = min < 10 ? '0' + min : min;
  var s = date1.getSeconds();
  s = s < 10 ? '0' + s : s;
  timestr = y + '年' + m + '月' + d + '日 ' + h + '时' + min + '分' + s + '秒';
  document.querySelector('#time').innerHTML = timestr;
}
var res;
window.onload = function () {
  res = setInterval(function () {
    getDate();
  }, 1000)
}
function stop() {
  clearInterval(res);
}
</script>
           

2. setTimeout()

间隔指定的毫秒数执行指定的代码一次

语法:setTimeout(“javascript function”, milliseconds);
  • 参数1 —— 函数(function)
  • 参数2 —— 间隔的毫秒数(1000 毫秒是一秒)

clearTimeout()

用于停止执行setTimeout()方法的函数代码。

语法:clearTimeout(timeoutVariable)
  • intervalVariable参数 是 setTimeout() 的返回值
<p>点击按钮,在等待 3 秒后弹出 "Hello"。</p>
<button onclick="hello()">点我3秒后弹出hello</button>
<button onclick="stoph()">点我停止弹框</button>
<script>
  var myvar;
  function hello() {
    myvar = setTimeout(function () {
      alert('hello!')
    }, 3000);
  }
  function stoph() {
    clearTimeout(myvar);
  }
</script>
           

继续阅读