js【详解】BOM

浏览器对象模型 (Browser obiect Mode 简称 BOM)
浏览器对象即 window,调用window对象的属性和方法时,可以省略window

window 常用的属性

Navigator

常用于获取浏览器的信息

navigator.userAgent;
  • 火狐浏览器范例:
    “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.28.10
    (KHTML, likeGecko) Version/6.0.3 Safari/536.28.10”
  • IE浏览器范例:
    “Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)”
  • 谷歌浏览器范例
    “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36”
// 可用于判断浏览器类型,但不精准(因为很多浏览器为了提升兼容性,在浏览器信息中放了很多不准确的信息)
const ua = navigator.userAgent;
const isChrome = ua.indexOf("Chrome");
console.log(isChrome);

其他使用场景

  • 统计访客的设备类型
  • 更具访客设备的不同,投放相应的广告等

实战场景 - 移动端适配

在 index.html 的 head 标签中添加

    <script>
      // 针对移动端,添加移动端样式前缀
      if (/iPhone|Android|Windows Phone/i.test(navigator.userAgent)) {
        document.body.classList.add('mobile-device')
        // 或直接跳转到专门的移动端页面  window.location.href = 'https://m.myweb.com'
      }
    </script>

Screen

// 显示屏的宽度(横向的分辨率)
screen.width; 

// 显示屏的高度(纵向的分辨率)
screen.height

它无法获取浏览器的宽高

location

可用于解析当前url

  • location.href 当前页面完整的 url
https://sunshinehu.blog.csdn.net/blogs?id=123456&&auth=sunshinehu#part1
  • location.origin 协议 + 主机名(域名) + 端口
http://43.140.200.74:8810
  • location.protocol 协议
https:
  • location.host 主机名 + 端口,如 search.phpied.com:8080
  • location.hostname 主机名(域名)
sunshinehu.blog.csdn.net
  • location.port 端口
8080
  • location.pathname 页面路径
/blogs
  • location.search 传入页面的参数,含 ?
?id=123456&auth=sunshinehu
  • location.hash 页面的 hash 值,即 # 后面的内容,包含 #
#part1

history

  • history.length 浏览器历史列表中的 url 数量
  • history.back(); 回退到上一个页面 (相当于点击浏览器顶部的左箭头)
  • history.forward(); 前进到下一个页面 (相当于点击浏览器顶部的右箭头)
  • history.go(整数); // 跳转到指定页面
history.go( 2 ); // 向前跳转两个页面
history.go( 1 ); // 向前跳转一个页面,相当于 history.forward()
history.go( 0 ); // 刷新当前页面
history.go( -1 ); // 向后跳转一个页面,相当于 history.back()
history.go( -2 ); // 向后跳转两个页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值