[作特效, 学JS] -- 13 加餐-聊聊BOM

什么是BOM和DOM

  • BOM => browser object model
  • DOM => document object model
  • 你能够这样理解
  • BOM就是浏览器, DOM就是浏览器里的网页

为何声明变量时, 不加var就是隐式的全局变量?

  • 浏览器里面,window对象(注意,w为小写)指当前的浏览器窗口。
  • 它也是当前页面的顶层对象,即最高一层的对象,全部其余对象都是它的下属。
  • 一个变量若是未声明,那么默认就是顶层对象的属性。
  • 因此会出现以下的状况
a = 1;
window.a // 1
复制代码
  • a是一个没有声明就直接赋值的变量,它自动成为顶层对象的属性

window对象

  • 最顶层的对象, 全部的其余对象, 都是它的属性
  • 由于是顶层对象, 也能够不写
  • documentwindow.document是一回事儿
  • document.getElementById()window.document.getElementById()是同样的
  • 你能够这样理解: 浏览器里面有网页, 因此 BOM.document就是DOM
  • 还有咱们熟悉的alert(), 其实是window.alert()

常见对象和属性

window.history

  • window.history属性指向 History 对象,它表示当前窗口的浏览历史
window.history.length // 3
history.back() // 后退到前一个网址
history.go(-1) // 同上

history.go(0); // 刷新当前页面
history.forward(); // 调到下一个记录
history.go(1); // 同上
复制代码

window.location

  • Location对象是浏览器提供的原生对象,提供 URL 相关的信息和操做方法。
  • 经过window.location和document.location属性,能够拿到这个对象。
  • Location.href:整个 URL。
  • Location.protocol:当前 URL 的协议,包括冒号(:)。
  • Location.host:主机,包括冒号(:)和端口(默认的80端口和443端口会省略)。
  • Location.hostname:主机名,不包括端口。
  • Location.port:端口号。
  • Location.pathname:URL 的路径部分,从根路径/开始。
  • Location.search:查询字符串部分,从问号?开始。
  • Location.hash:片断字符串部分,从#开始。
  • Location.username:域名前面的用户名。
  • Location.password:域名前面的密码。
  • Location.origin:URL 的协议、主机名和端口。
// 当前网址为
// http://user:passwd@www.example.com:4097/path/a.html?x=111#part1
document.location.href
// "http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
document.location.protocol
// "http:"
document.location.host
// "www.example.com:4097"
document.location.hostname
// "www.example.com"
document.location.port
// "4097"
document.location.pathname
// "/path/a.html"
document.location.search
// "?x=111"
document.location.hash
// "#part1"
document.location.username
// "user"
document.location.password
// "passwd"
document.location.origin
// "http://user:passwd@www.example.com:4097"
复制代码
  • 若是对Location.href写入新的 URL 地址,浏览器会马上跳转到这个新地址。
// 跳转到新网址
document.location.href = 'http://www.example.com';
复制代码
  • 直接改写location,至关于写入href属性。
document.location = 'http://www.example.com';
// 等同于
document.location.href = 'http://www.example.com';
复制代码
  • reload方法使得浏览器从新加载当前网址,至关于按下浏览器的刷新按钮。
// 向服务器从新请求当前网址
window.location.reload(true);
复制代码

专栏地图

相关文章
相关标签/搜索