JavaScript中的BOM

123 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情

BOM, Browser Object Model, 浏览器对象模型

DOM是用来访问网页的, 而BOM是用来访问和控制浏览器的各种属性和行为

window对象

在js中window对象是一个全局对象, 相当一个浏览器窗口实例

在js中分为全局作用域和函数作用域, 而在全局作用域中声明的变量, 对象, 函数, 都相当于在window对象向上添加了属性和方法

<script>
  let a = 3;
  let p = {name:'shaosiming', age: 18}
  function test() {
    console.log('test func');
  }
  console.log(window.name, age);
</script>

innerWidth, 当前网页的宽度

innerHeight, 当前网页的高度

outerWidth, 浏览器窗口的宽度

outerHeight, 浏览器窗口的高度

        console.log(innerWidth);
        console.log(innerHeight);
        console.log(outerWidth);
        console.log(outerHeight);

setTimeout方法

到了某个时间后, 就会执行回调函数, 只执行一次

第一参数为函数, 定时器到时间后要执行的方法, 第二个参数时间, 单位毫秒ms

setInterval方法

每隔一段时间就会执行回调函数, 只要不取消, 就一直执行

第一个参数为函数, 每次要执行的方法, 第二个参数, 间隔时间, 单位毫秒ms

        // 1s后执行一次
        let timer1 = setTimeout(() => {
            console.log('setTimeout');
        }, 1000);
        clearTimeout(timer1) // 取消定时器

        // 每1执行一次
        let timer2 = setInterval(() => {
            console.log('setInterval');
        }, 1000);

        // 5s后取消timer2
        setTimeout(() => {
            clearInterval(timer2)
        }, 5000);

dialog

alert, confirm, prompt

        // 一句话, 和一个确定按钮, 返回undefined
        // console.log(alert('hi, shaosiming, could I get your wechat?'));

        // 一句话, 一个输入框, 一个取消, 一个确定, 取消返回null, 确定rclk输入框中的内容
        // console.log(prompt('hi, dasiming, where is shaosiming?'));
        
        // 一句话, 一个取消, 一个确定, 取消返回false, 确定返回true
        console.log(confirm('hi, here is shaosiming!'));

navigator对象

appName, 浏览器名称, 如: Netscape

appVersion, 浏览器版本信息

platform, 操作系统平台信息, 如: MacIntel

userAgent, 每个浏览器都有不同的信息, 可以用此来区分不同的浏览器

location对象

存储了一些当前文档的信息

一些属性

href, 当前页面的完整的url地址 host + pathname

host: hostname + port

hostname: ip

port: 端口

pathname: 相当路径

protocol: 协议, http, https

一些方法

assign, 跳转到一个新的页面, 会有历史记录

reload, 刷新当前页面

replace, 替换当前页面, 新的页面替换旧的页面, 也就是说历史记录中存储的为新页面的记录

<body>
    <button id="assign">跳转页面</button>
    <button id="reload">刷新页面</button>
    <button id="replace">替换页面</button>
</body>
<script>
    document.getElementById('assign').onclick = function() {
        location.assign('17_bom2.html');
    }

    document.getElementById('reload').onclick = function() {
        location.reload();
    }

    document.getElementById('replace').onclick = function() {
        location.replace('17_bom2.html');
    }
</script>

screen对象

width, 屏幕的总宽度

height, 屏幕的总高度

availWidth, 除去菜单栏的宽度

availHeight, 除去菜单栏的高度

history对象

length属性, 历史记录的数量

forward, 历史记录中前面的一个页面

back, 历史记录中后退一个页面

go, 如果参数为正, 则是前进, 为1时相当于forward; 如果参数为负, 则是后退, 为-1时, 相当于back

    document.getElementById('forward').onclick = function() {
        history.forward();
    }

    document.getElementById('back').onclick = function() {
        history.back();
    }

    document.getElementById('go').onclick = function() {
        history.go(-2);
    }