JavaScript从放弃到入门(四)| JS操作BOM

2021/6/10 12:24:34

本文主要是介绍JavaScript从放弃到入门(四)| JS操作BOM,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录

1 window对象

2 navigator 对象

3 screen对象

4 location

5 document

6 history


BOM(Browser Object Model)即浏览器对象模型

浏览器对象模型 (BOM) 使 JavaScript 有能力与浏览器"对话"。

BOM浏览器对象模型提供了一些基本的对象让我们操作。操作BOM也就是操作它为我们提供的这些对象的属性。

这里对BOM的属性和方法都做一个说明。

1 window对象

  • 所有浏览器都支持 window 对象。它表示浏览器窗口。

  • 所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。

  • 全局变量是 window 对象的属性。

  • 全局函数是 window 对象的方法。

  • 甚至 HTML DOM 的 document 也是 window 对象的属性之一

 

我们可以直接通过window.property=值 直接赋值的方式来对属性进行修改。但是有些地方要注意的是有些属性是只读,只能获取值,修改并不会生效。

window的一些方法。

 

很多方法使用的并不频繁,我们常用的有

alter():显示带有一段消息和一个确认按钮的警告框。

alert("ok") //不返回值,只提示消息

confirm():显示带有一段消息以及确认按钮和取消按钮的对话框。

var ok = confirm("ok")  //选择确定。
ok              //true

open():打开一个新窗口。

open("/s?wd=ss")    //在域名的基础上跳转页面

2 navigator 对象

navigator 对象包含有关浏览器的信息。

  • navigator .appName:浏览器名称;

  • navigator .appVersion:浏览器版本;

  • navigator .language:浏览器设置的语言;

  • navigator .platform:操作系统类型;

  • navigator .userAgent:浏览器设定的 User-Agent 字符串。

navigator.appName
"Netscape"
navigator.appVersion
"5.0 (Windows)"
navigator.language
"zh-CN"
navigator.platform
"Win32"
navigator.userAgent
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0"

属性值信息可以被修改,因此有时读取的并不准确。

3 screen对象

screen 对象表示屏幕的信息,常用的属性有:

  • screen.width:屏幕宽度,以像素为单位;

  • screen.height:屏幕高度,以像素为单位;

  • screen.colorDepth:返回颜色位数,如8、16、24。

screen.width
1366
screen.height
768
screen.colorDepth
24

4 location

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

https://search.bilibili.com/all?keyword=java%E5%9F%BA%E7%A1%80%E5%B0%9A%E7%A1%85%E8%B0%B7&from_source=web_search

获取URL的信息

 

window.location.href
"https://search.bilibili.com/all?keyword=java%E5%9F%BA%E7%A1%80%E5%B0%9A%E7%A1%85%E8%B0%B7&from_source=web_search"
window.location.protocol
"https:"
window.location.host
"search.bilibili.com"
window.location.port
""
window.location.pathname
"/all"
window.location.search
"?keyword=java%E5%9F%BA%E7%A1%80%E5%B0%9A%E7%A1%85%E8%B0%B7&from_source=web_search"
window.location.hash
""

5 document

document 对象表示当前页面。由于HTML在浏览器中以DOM形式表示为树形结,document 对象就是整个DOM树的根节点。

常用的document属性

document.cookie //获取用户的cookie信息。

document.scripts //返回页面中所有脚本的集合

document.title //获取文件title属性

document.URL //返回文件完整URL

document. getElementsById() //获取一个指定id的标签

document.getElementsByTagName() //获取一组指定标签名的集合。

document. getElementsByClassName() //获取一组指定类名的集合。

document可以有效的对标签元素进行操作。

6 history

history不建议再使用。



这篇关于JavaScript从放弃到入门(四)| JS操作BOM的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程