前端 -- JavaScript-BOM

11.3.17 BOM

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

window对象:

  • window对象是JavaScript中的顶级对象

  • 全局变量、自定义函数也是window对象的属性和方法。

  • window对象下的属性和方法调用时,可以省略window。

window.open(url,target)

//url:要打开的地址。
//target:新窗口的位置。可以是:_blank 、_self、 _parent 父框架。

window.close() - //关闭当前窗口 (只能关闭用js的window.open()打开的页面,了解)
   
window.innerHeight - 浏览器窗口的内部高度
window.innerWidth - 浏览器窗口的内部宽度

1. 定时器

  • setInterval

setInterval : 每隔一段时间就完成某个操作

var tid = setIterval("func()",n) //每隔n毫秒就调用一次func函数
var tid = setInterval(func,n)

calearInterval(tid) //清除定时器
  • setTimeout

setTimeout : 每隔一段时间之后执行一次来完成某个操作
var tid = setTimeout(fn,n) //n毫秒之后只调用一次fn函数
var tid = setTimeout("fn()",n)

clearTimeout(tid) //清楚定时器
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<style>
  .box{
       width: 100px;
       height: 100px;
       background-color: lightcoral;
  }
</style>
<body>
   <div id="box" class="box"></div>
</body>
<script>
   // window.setTimeout(fn,2000)
   // function fn() {
   //     alert('两秒后弹出警告框...')
   // }
   setInterval(fn,500)  // 每0.5秒调用一次函数
   function fn() {
       var box = document.getElementById('box') //获取事件对象
       box.classList.toggle('box') // 如果存在class='box'就删除,不存在就添加
  }
</script>
</html>

2. location对象

window的子对象 : window.location

属性:
window.location.href //查看当前网页的url
window.location.href='http://www.baidu.com' //修改当前网页的url.修改之后会跳转
方法:
window.location.reload() //刷新页面

3. navigator对象

window.navigator 的一些属性可以获取客户端的一些信息。

  • userAgent:系统,浏览器)

  • platform:浏览器支持的系统,win/mac/linux

console.log(navigator.userAgent);
console.log(navigator.platform);

4. history对象

// 后退:
history.back()
history.go(-1):0是刷新

// 前进:
history.forward()
history.go(1)

5. screen对象

screen.availWidth  //可用的屏幕宽度
screen.availHeight //可用的屏幕高度

6. onscroll事件

window.onscroll //在页面的滚动条滚动的时候触发的事件
document.documentElement.scrollTop //针对获取浏览器的垂直滚动条的位置
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<style>
   div{
       height: 2000px;
  }
   a{
       display: none;
       position: fixed;
       bottom: 20px;
       right: 20px;
  }
</style>
<body>
   <div></div>
   <a href="#" id="back">回到顶部</a>
</body>
<script>
   window.onscroll = function () {
       var a = document.getElementById('back')
       console.log(document.documentElement.scrollTop)
       if(document.documentElement.scrollTop>500){
           a.style.display = 'block'
      }else{
           a.style.display = 'none'
      }
  }
</script>
</html>
posted on 2019-08-20 22:03  ShenQiang  阅读(398)  评论(0编辑  收藏  举报