Bom相关使用

1 Bom

1.1 Bom概述

JavaScript由三大核心模块组成:

  • javascript基础语法(ECMAScript基础语法)
  • DOM(Document Object Model)
  • BOM(Browser Object Model)

其中BOM指的是由浏览器自身的特性和对象组成的元素,例如window,screen,history等跟浏览器相关的元素,通常这些元素由各自的浏览器厂商决定,因此存在兼容问题,例如在不同的浏览器中弹窗效果存在不同;BOM包含以下元素:

  • window
  • document
  • navigator
  • screen
  • location
  • history
  • cookie等存储元素

1.2 常用Bom存储对象

1.2.1 window

BOM的顶层对象window,因此一些其他的Bom对象都是window的子对象,全局的this指针指向的就是window对象window代表的就是当前的浏览器窗口,内部包含了关于窗口的信息(大小,预定义函数):

1.2.1.1 常用属性
  • innerWidth:浏览器内部可显示区域的宽度
  • innerHeight:浏览器内部可显示区域的高度
  • outerWidth:浏览器宽度
  • outerHeight:浏览器高度
    window属性
1.2.1.2 常用函数
  • 弹窗类
    • alert():警告框
    • confirm():确认框
    • prompt():消息输入框
    • open():自定义窗口
<body>
<button id="dialog1">警告框</button>
<button id="dialog2">确认框</button>
<a href="javascript:if(window.confirm('确认开通会员吗?'))alert('开通成功')">开通SSSSSSSSSSSSVip</a>
<button id="dialog3">消息框</button>
<button id="dialog4">自定义窗口</button>


</body>
<script>
    console.log('浏览器内部高度=' + this.innerHeight);
    // 内部宽度会根据内容进行变化
    console.log('浏览器内部宽度=' + this.innerWidth);
    console.log('浏览器宽度=' + window.outerWidth);
    console.log('浏览器高度=' + window.outerHeight);

    function $(id) {
        return document.getElementById(id);
    }

    //警告框
    $('dialog1').addEventListener('click', function () {
        window.alert('警告警告');
        //如果不处理警告框,就会导致后续内容阻塞
        console.log(123);
    })
    //确认框
    $('dialog2').addEventListener('click', function () {
        // 结果时boolean类型,如果点击了确认,结果true
        var b = window.confirm('是否要加入星条红?');
        console.log(b);
    })
    //消息框
    $('dialog3').addEventListener('click', function () {
        //消息输入框:需要两个参数,参数1:提示信息,参数2:默认值,返回值就是输入的值
        var b = window.prompt('请示你是Alex吗', '是');
        console.log(b)
    });
    //自定义窗口
    $('dialog4').addEventListener('click', function () {
        //开启自定义窗口
        var w = window.open('http://www.ruandy.com','_blank','width=800,height=400,top=300,left=500');
        //一整个window对象
        console.log(w);
    })
</script>

setTimeout(fun,delay):定时器,延迟指定时间之后执行回调函数

var i = 5;
    (function leave() {
        document.getElementById('num').innerText = i;
        i--;
        if (i < 0) {
            //清理定时器
            clearTimeout(flag);
            //跳转
            location.href = 'code.html';
        }
        //启动定时任务,每隔1s执行
        flag = setTimeout(leave, 1000);
        console.log(flag)
    })();

setInterval(fun,delay):定时器,间隔指定时间反复执行回调
回到顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            margin: 0 auto;
            width: 1800px;
            height: 3000px;
            background: linear-gradient(135deg, #92ffc0, #002661)
        }

        .backTop {
            position: fixed;
            right: 40px;
            bottom: 40px;
            z-index: 999;
            width: 80px;
            height: 80px;
            color: #fff;
            background: #dd7694;
            /*文本横向居中*/
            text-align: center;
            /*文本纵向居中*/
            line-height: 80px;
            // 鼠标经过变小手样式
            cursor: pointer;
            // 动画效果
            transition: opacity .5s;
            /*透明度 0.0-1.0*/
            opacity: 0.0;
        }
        // 鼠标悬停
        .backTop:hover {
            background: #222;
        }
    </style>
</head>
<body>
<div class="backTop">回到顶部</div>
<div class="box"></div>
</body>
<script>
    //透明度
    var op = 0.0
    //当滚动条在一定位置时才显示按钮
    window.addEventListener('scroll', function () {
        //获取当前滚动条和文档顶部的距离
        var sc = document.body.scrollTop || document.documentElement.scrollTop;
        console.log(document.body.scrollTop || document.documentElement.scrollTop)
        if (sc > 400) {
            //逐渐显示
            let flag = setInterval(function () {
                document.querySelector('.backTop').style.opacity = (op += 0.1);
                if (op >= 1.0) clearInterval(flag);
            }, 50);
        } else {
            //逐渐隐藏
            let flag = setInterval(function () {
                document.querySelector('.backTop').style.opacity = (op -= 0.1);
                if (op <= 0.0) clearInterval(flag);
            }, 50);
        }
    });
    //回到顶部
    document.querySelector('.backTop').addEventListener('click', function () {
        //获取当前滚动条和文档顶部的距离
        let h = document.body.scrollTop || document.documentElement.scrollTop;
        let i = 1;
        //启动定时器
        flag = setInterval(function () {
            h -= (10 * (i++));
            document.body.scrollTop = document.documentElement.scrollTop = h;
            if (h <= 0) {
                //关闭定时器
                clearInterval(flag);
            }
        }, 50);
    })

</script>
</html>

let h = document.body.scrollTop || document.documentElement.scrollTop;
两者都是获取当前滚动条和文档顶部的距离
前者在W3C浏览器中取值为0
当两者中有一个值有意义时,就取这个值,另一个无效

1.2.2 document

document表示的是整个html文档对象,是window对象中的子对象,document即DOM数节点中的根节点<html></html>,常见属性方法如下:

  • title:设置网页标题
  • body:获取页面的body部分
  • forms:获取当前文档中所有的表单元素
  • links:获取文档中所有的超链接
  • images:获取文档中所有的图片元素
  • write():向文档中写入内容(追加)
  • writeln():向文档中写入内容(追加),支持换行
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>page1</h1>
<img src="img/八神庵_219-0.png" alt="">
<img src="img/八神庵_219-1.png" alt="">
<img src="img/八神庵_219-2.png" alt="">

<form action="" class="f1">
    <input type="text" name="username" value="softeem">
</form>

<form action="" class="f2">
    <a href="">链接1</a>
    <a href="">链接2</a>
    <a href="">链接3</a>
    <a href="">链接4</a>
    <a href="">链接5</a>
    <a href="">链接6</a>
</form>
</body>
<script>
    //获取当前页面对象
    var d = window.document;
    //设置页面的标题
    d.title = '通过JS设置的标题';
    // d.write('<span>HelloJS</span>')
    // d.writeln('<span>你好</span><br>', '<span>好不了一点</span>')

    //获取文档中的body部分
    let body = d.body;
    console.log(body)

    //获取文档中的所有的img元素
    let img = d.images;
    //获取当前页面中的第一章图片
    console.log(img[0])
    console.log(img[0].src)

    //获取文档中的所有表单对象
    let form = d.forms;
    console.log(form)
    console.log(form[0].username.value)

    //获取文档上的所有超链接
    let link = d.links;
    console.log(link)
</script>
</html>

writerln():document.writeln(d + “
”);

1.2.3 navigator

navigator对象表示的是当前浏览器的信息,常用属性如下:

  • appName:浏览器名称
  • appVersion:浏览器版本
  • language:浏览器设置的语言
  • platform:操作系统类型
  • userAgent:浏览器设置的User-Agent字符串
<script>
    console.log('appName-'+navigator.appName);
    console.log('appVersion-'+navigator.appVersion);
    console.log('language-'+navigator.language);
    console.log('platform-'+navigator.platform);
    console.log('userAgent-'+navigator.userAgent);
</script>

1.2.4 screen

screen表示客户端的屏幕的信息,常见属性如下:

  • height:屏幕高度
  • width:屏幕宽度
  • availHeight:可用高度
  • availWidth:可用宽度
<script>
    let screen = window.screen;
    console.log(screen.width)
    console.log(screen.height)
    console.log(screen.availWidth)
    console.log(screen.availHeight)

    //响应式图片:根据窗口大小图片的大小自适应
    window.addEventListener('resize', r);

    function r() {
        document.images[0].width = window.innerWidth;
        document.images[0].height = window.innerHeight;
        document.images[0].src = 'img/16.jpg';
    }

    r();
</script>

1.2.5 location

location对象表示当前页面的URL信息,例如:一个完成的URL如下

http://www.example.com:8080/path/index.html?a=1&b=2#TOP

可以用location.href获取,可以单独获取URL各个部分的值

location.protocol;//‘https’ location.host;//‘www.baidu.com’
location.port;//‘8080’ location.pathname;//‘/path/index.html’
location.search;//‘a=1&b=2’

<body>
<form action="">
    <input type="text" name="path" placeholder="请输入页面名称"><br>
    <button type="button" class="btn1">跳转到指定页面</button>
    <button type="button" class="btn2">替换页面</button>
    <button type="button" class="btn3">重新加载页面</button>
</form>
</body>
<script>
    console.log(window.location)
    //通过输入框输入跳转到指定的页面
    document.querySelector('.btn1').addEventListener('click',function (){
        // location.href = document.forms[0].path.value;
        location.assign(document.forms[0].path.value)
    });
    //替换当前页面,无法撤回
    document.querySelector('.btn2').addEventListener('click',function (){
        location.replace(document.forms[0].path.value);
    })

    //重新加载当前页面
    document.querySelector('.btn3').addEventListener('click',function (){
        location.reload();
    })

</script>

一个属性三个方法

  • location.href
  • location.assign()
  • location.replace()
  • location.reload()

1.2.6 history

history对象保存了浏览器的历史记录,JavaScript可以调用history对象的back()forward (),相当于用户点击了浏览器的“后退”或“前进”按钮。

这个对象属于历史遗留对象,对于现代Web页面来说,由于大量使用AJAX和页面交互,简单粗暴地调用history.back()可能会让用户感到非常愤怒。

任何情况,你都不应该使用history这个对象了。

1.3 Bom存储

在JS的BOM中,提供的对象除了以上的这些之外,另外对于数据的缓存也提供了两种方案,第一种方案:cookie,另外一种是跟随H5的出现新增的本地存储:localStorage&sessionStorage;

1.3.1 cookie

cookie是一项用于客户端浏览器使用文件技术进行本地存储的存储机制,特点是:

  1. 存储在客户端中
  2. 可以被客户端浏览器读取
  3. 在请求到服务端时cookie也可以被传送到服务端
  4. 只能存储字符串数据
  5. 单个cookie最大的存储大小4kb
  6. 一个域中最多支持20个
  7. 存储方式是键值对结构(name=value)

cookie的组成部分

  1. 数据(键值对)
  2. 有效期(默认生命周期和session保持一致:即浏览器关闭就消失)
  3. 作用域
1.3.1.1 使用方法

document.cookie

    // document.cookie = `周杰伦=周杰伦;expires=${d.toString()}`;
    // document.cookie = `pwd=123456;expires=${d.toString()}`;

使用注意事项:

  1. 如果需要存储多个cookie只需要多次调用document.cookie即可
  2. cookie的获取也是通过document.cookie进行获取,如果有多个cookie的存在,则会使用;拼接在一起
1.3.1.2 封装通用的cookie操作

code.ls

//添加cookie(键,值,有效期)
function addCookie(key, value, expDay) {
    //创建日期对象
    let d = new Date();
    //在原有的基础添加指定天数
    d.setTime(d.getTime() + expDay * 24 * 60 * 60 * 1000);
    //设置cookie
    document.cookie = `${key}=${value};expires=${d.toString()};path=/`;
}

//根据cookie的键获取值
function getCookie(key) {
    //获取所有的cookie
    let cookies = document.cookie;
    //使用;作为分割符将获取到的所有cookie转换成数组
    cookies = cookies.split(';');
    //遍历数组
    for (c in cookies) {
        //获取每一个cookie对象
        let item = cookies[c].trim();
        item = item.split('=');
        if (key == item[0]) {
            return item[1];
        }

    }
}

1.3.2 sessionStorage&localStorage

在HTML5出现之后 ,W3C在浏览器存储方面新增了两个用于本地缓存的对象sessionStorage/localStorage;这两个存储对象时对cookie存储的补充和完善,以上两个对象具备相同的一套api:

  • setItem(key,valuye):设置存储的键和值
  • getItem(key):通过键获取值
  • removeItem(key):通过键删除元素
  • clear():清空所有元素
<script>
    var user = {
        id: 1001,
        name: 'softeem',
        age: 18,
        group: {
            id: 1,
            name: '小王'
        }
    }
    //添加到sessionStorage
    document.getElementById('add1').addEventListener('click', function () {
        sessionStorage.setItem('msg', JSON.stringify(user));
    })
    //取出sessionStorage的内容
    document.getElementById('get1').addEventListener('click', function () {
        let msg = sessionStorage.getItem('msg');
        console.log(JSON.parse(msg))
    })
    //清空sessionStorage
    document.getElementById('clear1').addEventListener('click', function () {
        sessionStorage.clear();
    })
//---------------------------------------------------------------------------------------------------------
    //添加到localStorage
    document.getElementById('add2').addEventListener('click', function () {
        localStorage.setItem('msg', JSON.stringify(user));
    })
    //取出localStorage的值
    document.getElementById('get2').addEventListener('click', function () {
        let msg = localStorage.getItem('msg');
        console.log(JSON.parse(msg))
    })
    //清空localStorage
    document.getElementById('clear2').addEventListener('click', function () {
        localStorage.clear();
    })

</script>
1.3.2.1 sessionStorage

该存储对象的有效时间与session一致,session一旦失效,或者被清理,则该存储对象中的数据也会被清除

1.3.2.2 localStorage

该对象的数据只要不手动清理,则一直存在(长期存储)

h5新增存储API和cookie的区别

  1. 提供了更简单的存储方式
  2. 存储空间大小无限制
  3. cookie在每次访问服务器端时都会被上传到我们的服务器端,sessionStorage/localStorage无序传递到服务器端
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值