BOM定义
浏览器对象模型,可以使我们通过JS来操作浏览器,在BOM中为我们提供了一组对象,用来完成的浏览器的操作。
BOM对象
- Window:代表整个浏览器的窗口,同时window也是网页中的全剧对象。常用: alert()/ confirm()/ prompt()。其他用法褥定时器见下一章节
- Navigator: 代表当前浏览器的信息,通过该对象可以识别不同浏览器。由于历史原因,navigator对象的中大部分属性的已经不鞥帮助我们识别浏览器,一般我们会用userAgent来判断浏览器信息。userAgent是一个字符串,这个字符串会有用来描述浏览器信息的内容
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <style> </style> <script> console.log(navigator.userAgent) //Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:91.0) Gecko/20100101 Firefox/91.0 //Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36 //Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15 var ua = navigator.userAgent; if (/firefox/i.test(ua)) { alert("你是火狐!!"); } else if (/chrome/i.test(ua)) { alert("你是chrome!!"); } </script> </head> <body> </body> </html>
- Location:代表当前浏览器地址栏信息,通过location可以后获取地址栏信息,或者操作浏览器跳转页面风格。方法:location.assign()/location.reload()/location.replace()
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <style> </style> <script> window.onload = function () { var btn = document.getElementById('btn'); btn.onclick = function () { /* 如果直接打印location,则可以获取地址栏的信息(当前页面的完整路径) alert(location); */ /* 如果直接将location属性修改为一个完整路径,或者是相对路径,则我们页面会自动跳转改路径,而且会生成相应的历史记录 location ="http://www.baidu.com"; */ /* assgin()用来跳转其他页面,作用和直接修改location一样 location.assign("http://www.baidu.com"); */ /* reload()用于家在当前页面, 作用和刷新按钮一样 如果在当法中传递一个true,作为参数,则会强制清空的刷新缓存 location.reload(true);*/ /* 可以使用一个新的页面的替换当前也买呢,调用完毕也会跳转页面, 不会生成历史记录,不能使用回退按钮会退。 */ location.replace("test01.html"); } } </script> </head> <body> <h1>Location </h1> <button id="btn">点我一下</button></br> <input type="text"> </body> </html> [点击并拖拽以移动]
- History: 代表浏览器的历史记录, 可以通过的的该对象来操作浏览器的历史记录。由于隐私原因,该对象不能获取具体的历史记录,只能操作的浏览器向前向后翻页。而且 该操作只在当次访问时有效。方法: history.length/history.back()/history.forward()/history.go
-
//test01.html <!DOCTYPE html> <html> <head> <meta charset="utf8"> <style> </style> <script> </script> </head> <body> <h1>test 01 </h1> <a href="test02.html">去test02</a> </body> </html> //test02.html <!DOCTYPE html> <html> <head> <meta charset="utf8"> <style> </style> <script> </script> </head> <body> <h1>test 02 </h1> <a href = "history.html">去History</a> </body> </html> //history.html <!DOCTYPE html> <html> <head> <meta charset="utf8"> <style> </style> <script> //alert(history.length); window.onload = function(){ var btn = document.getElementById('btn'); btn.onclick = function(){ //history.back() //history.forward(); history.go(-2) } } </script> </head> <body> <h1>History </h1> <button id="btn">点我一下</button></br> <a href = "day14.html">day14</a> </body> </html>
- Screen:代表用户的屏幕的信息,通过该对象可以获取用户的 现实器的相关信息
这些BOM对象在浏览器的中都是作为window对象的的属性保存,可以通过window对象来使用, 也可以直接使用