BOM(浏览器对象模型)
所有浏览器都支持window对象,他表示浏览器窗口。
所有js全局对象,函数,变量均自动成为window对象的成员。
全局变量是window对象的属性。
全局函数是window对象的方法。
基于html dom的document也是window对象的属性之一。
1 2 | window.document.getElementById("header"); document.getElementById("header"); |
1. window 获取浏览器c窗口尺寸
浏览器窗口的内部高度(不包括滚动条,菜单栏,工具栏)
1 2 | window.innerHeight window.innerWidth |
适用于Internet Explorer 8、7、6、5浏览器的window如下:
1 2 | document.documentElement.clientHeight document.documentElement.clientWidth |
兼容方案获取浏览器宽高`
1 2 | var width=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth var height=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight |
2. screen 获取电脑屏幕大小
属性返回访问者屏幕的宽/高度,以像素计,减去界面特性,比如窗口任务栏。
screen.availWidth
screen.availHeight
3. window 开启关闭窗口
开启:window.open()
关闭:window.close()
1 2 3 4 5 6 7 8 9 | <script type= "text/javascript" > var newWindows; function newWindow() { } function closeWindow() { newWindows.close(); } </script> |
4. 浏览器事件
名称 | 描述 |
---|---|
window.onload | 浏览器加载事件 |
window.onscroll | 浏览器滚动监听 |
window.onresize | 浏览器缩放监听 |
window.open | 打开事件 |
window.close | 关闭 |
5. location
名称 | 描述 |
---|---|
location.herf | 当前url |
location.hostname | 主机域名 |
location.pathname | 当前页面路径和文件名 |
location.port | 端口 |
location.protocol | 协议(http/https) |
location.assign | 加载新的文档 |
location.search | url参数 |
1 2 3 4 5 | console.log(location.href); console.log(location.hostname); console.log(location.pathname); console.log(location.port); console.log(location.protocol); |
6. history
浏览器历史,可以不用写window这个前缀
名称 | 描述 |
---|---|
history.length | 次数 |
history.back | 上一页 |
history.forward | 下一页 |
history.go |
小括号中,设定数值和 正负号,+数值 向下一个跳转的次数,-数值 向上一个跳转的次数,次数计算 : 结束页面 - 起始页面 ,错误跳转次数,没有执行效果 |
window.history.back();
7. navigator 获取浏览器相关信息
window.navigator
名称 | 描述 |
---|---|
navagator.userAgent | 型号,内核,版本,平台 |
navagator.appVersion | 浏览器版本信息 |
navagator.appName | 浏览器名称 |
navagator.platform | 操作系统 |
navagator.geolocation | 位置信息包括经度longitude和纬度latitude |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | export function GetCurrentBrowser() { var agent = navigator.userAgent.toLowerCase(); var regStr_ie = /msie [\d.]+;/gi; var regStr_ff = /firefox\/[\d.]+/gi var regStr_chrome = /chrome\/[\d.]+/gi; var regStr_saf = /safari\/[\d.]+/gi; //IE11以下 if (agent.indexOf( "msie" ) > 0) { return agent.match(regStr_ie); } //IE11版本中不包括MSIE字段 if (agent.indexOf( "trident" ) > 0 && agent.indexOf( "rv" ) > 0) { return "IE " + agent.match(/rv:(\d+\.\d+)/)[1]; } //firefox if (agent.indexOf( "firefox" ) > 0) { return agent.match(regStr_ff); } //Chrome if (agent.indexOf( "chrome" ) > 0) { return agent.match(regStr_chrome); } //Safari if (agent.indexOf( "safari" ) > 0 && agent.indexOf( "chrome" ) < 0) { return agent.match(regStr_saf); } } // get os export function GetOs() { let userAgent = navigator.userAgent.toLocaleLowerCase() //toLocaleLowerCase()将字母转小写 let wins = [ { sys: 'windows nt 5.0' , alias: 'windows 2000' , name: 'Win2000' }, { sys: 'windows nt 5.1' , alias: 'windows xp' , name: 'WinXP' }, { sys: 'windows nt 5.2' , alias: 'windows 2003' , name: 'Win2003' }, { sys: 'windows nt 6.0' , alias: 'Windows Vista' , name: 'WinVista' }, { sys: 'windows nt 6.1' , alias: 'Windows 7' , name: 'Win7' }, { sys: 'windows nt 6.2' , alias: 'Windows 8' , name: 'Win8' }, { sys: 'windows nt 10.0' , alias: 'Windows 10' , name: 'Win10' }, ] for (let win of wins) { if (userAgent.indexOf(win.sys) > -1 || userAgent.indexOf(win.alias) > -1) { return win.name } } } export function getEdition() { var userAgent = navigator.userAgent.toLocaleLowerCase() if (userAgent.indexOf( "win64" ) > -1 || userAgent.indexOf( "wow64" ) > -1) { return '64位' } else { return '32位' } } export function IsPC() { var userAgentInfo = navigator.userAgent; var Agents = [ "Android" , "iPhone" , "SymbianOS" , "Windows Phone" , "iPad" , "iPod" ]; var flag = true ; for ( var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false ; break ; } } return flag; } //获取url参数 返回对象 export function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = {} let strs = [] if (url.indexOf( "?" ) != -1) { var str = url.substr(1); strs = str.split( "&" ); for ( var i = 0; i < strs.length; i++) { theRequest[strs[i].split( "=" )[0]] = unescape(strs[i].split( "=" )[1]); } } return theRequest; } export const browser = { versions: ( function () { let u = navigator.userAgent // let app = navigator.appVersion return { trident: u.indexOf( 'Trident' ) > -1, // IE内核 presto: u.indexOf( 'Presto' ) > -1, // opera内核 webKit: u.indexOf( 'AppleWebKit' ) > -1, // 苹果、谷歌内核 gecko: u.indexOf( 'Gecko' ) > -1 && u.indexOf( 'KHTML' ) === -1, // 火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端 android: u.indexOf( 'Android' ) > -1 || u.indexOf( 'Adr' ) > -1, // android终端 iPhone: u.indexOf( 'iPhone' ) > -1, // 是否为iPhone或者QQHD浏览器 iPad: u.indexOf( 'iPad' ) > -1, // 是否iPad webApp: u.indexOf( 'Safari' ) === -1, // 是否web应该程序,没有头部与底部 weixin: u.indexOf( 'MicroMessenger' ) > -1, // 是否微信 qq: u.match(/\sQQ/i) === 'qq' // 是否QQ } }()), language: (navigator.browserLanguage || navigator.language).toLowerCase() } |
8. 弹窗
1、警告框:Window.alert()
2、输入框:Window.prompt()
3、确认框: Window.confirm()
DOM (文档对象模型)
通过 HTML DOM,使用 JavaScript访问 HTML 文档的所有元素。
当网页被加载时,浏览器会创建页面的文档对象模型
DOM 分类
定义了访问和操作 HTML 文档的标准方法。DOM 将 HTML 文档表达为树结构
html中,一切都是节点
- 元素节点
- 文本节点
- 属性节点
各个节点关系为:父子关系\兄弟关系
通过可编程的对象模型,JavaScript 获得了足够的能力来创建动态的 HTML
- JavaScript 能够改变页面中的所有 HTML 元素。
- JavaScript 能够改变页面中的所有 HTML 属性。
- JavaScript 能够改变页面中的所有 CSS 样式。
- JavaScript 能够对页面中的所有事件做出反应。
DOM对象
对象 | 描述 |
---|---|
Document:文档对象 | 每个载入浏览器的 HTML 文档都会成为 Document 对象 |
Element:元素对象 | Element 对象可以拥有类型为元素节点、文本节点、注释节点的子节点。 |
Attribute:节点属性对象 | Attr 对象表示 HTML 属性 |
Event:事件对象 | 事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状 |
Document文档对象
Document对象所有属性
属性 | 描述 |
---|---|
document.body | 获取body |
document.Head | 获取head |
document.Element | 获取html |
document.cookie | 获取cookie |
document.domain | 当前文档域名,可做跨域操作 |
document.lastModified | 文档最后修改日期时间 |
document.referrer | 当前文档的url |
document.title | 标题 |
document.URL | 当前文档的URL |
Document常用方法
方法 | 描述 |
---|---|
document.write() | 文档写入内容 |
document.open() | 打开一个流,以收集来自任何 document.write() 或 document.writeln() 方法的输出。 |
document.close() | 关闭用 document.open() 方法打开的输出流,并显示选定的数据。 |
document.writeIn() | 等同于 write() 方法,不同的是在每个表达式之后写一个换行符 |
获取元素 | |
document.getElementById() | 通过id获取元素 |
document.getElementsByName() | 通过name获取相关元素数组 |
document.getElementsByTagName() | 通过标签获取相关元素数组 不能使用forEach循环 |
document.getElementsByClassName() | 通过class获取相关元素数组 不能使用forEach循环 |
document.querySelector() | 获取第一个匹配条件的标签对象 --- 只会获取一个标签对象 |
document.querySelectorAll() | 获取所有匹配条件的标签对象 执行结果是伪数组 |
创建元素 | |
document.createAttribute() | 创建属性对象 |
document.createElement() | 创建元素对象 |
document.createTextNode() | 创建文本对象 |
document.createComment() | 创建注释 |
element文档对象
element元素对象常用的方法
方法 | 描述 |
---|---|
元素增,删,改,克隆 | |
appendChild(doc) | 插入节点到最后 |
insertBefore(ndoc, oldoc) | 插入节点到某个节点之前 |
removeChild(doc) | 移除该节点 |
replaceChild(doc) | 替换节点 |
cloneNode() | 克隆节点 |
cloneNode(true) | 克隆节点及其内容 |
属性相关 | |
getAttribute() | 获取属性 |
setAttribute() | 设置属性 |
removeAttribute() | 移除属性 |
getAttributeNode() | 指定属性节点 |
setAttributeNode() | 设置属性节点 |
removeAttributeNode() | 移除属性节点 |
getElementsByTagName() | 指定标签名的所有子元素的集合 |
nodelist.item() | NodeList 中位于指定下标的节点 |
element元素对象常用的属性
属性 | 描述 |
---|---|
id | 元素id |
style | 样式 |
className | class属性 |
innerHML | 标签内容 |
innerText | 文本内容 |
获取节点 | |
childNodes | 获取元素子节点 |
parentNode | 获取元素父节点 |
attributes | 获取所有属性 |
children | 获取所有标签子节点 |
firstchild | 第一个子节点 |
lastchild | 最后一个子节点 |
firstElementchild | 第一个标签子节点 |
lastElementChild | 最后一个标签子节点 |
previousSibling | 上一个兄弟节点 |
nextsibling | 下一个兄弟节点 |
previousElementsibling | 上一个标签 |
nextElemntSibling | 下一个标签 |
parentNode | 父级节点 |
parentElement | 父级标签节点 |
nodeName | 名字:元素节点--标签名称、属性节点--属性名、文本节点--#text、注释节点--#comment |
nodeType | 节点类型:1元素, 2属性 3文本, 8注释 |
nodeValue | 元素值:属性值、文本内容、注释内容 |
nodelist.length | NodeList 中的节点数 |
尺寸距离 | |
clientHeight | 高度-内容+padding |
Clientwidth | 宽度 |
offsetHeight | 高度-内容+padding+border |
Offsetwidth | 宽度 |
ClientTop | 上边框宽度 |
clientLeft | 做边框宽度 |
offsetTop | 父物体顶部距离 |
offsetLeft | 父物体左侧距离 |
DOM事件操作
鼠标事件
名称 | 描述 |
---|---|
click | 点击事件 |
dbclick | 双击事件 |
contextmenu | 右键点击事件 |
mousedown | 按下事件,执行一次 |
mouseup | 抬起事件 |
mousemove | 鼠标移动 |
mouseover | 移入 |
mouseout | 移除 |
mouseenter | 移入,不发生冒泡 |
mouseleave | 移除,不冒泡 |
键盘事件
获取点击时的事件对象
- 普通版本
E/event
- IE低版本
Window.event
兼容写法:var e=e||window.event
获取案件相关
- 按键名称:
e.Key
- 按键编码:
e.Keycode
- 兼容火狐:
e.Which
兼容写法: e.Keycode|| e.Which
altkey ctrlkey shiftkey 判断是否按下 alt ctrl shift
触屏事件
名称 | 描述 |
---|---|
touchstart | 开始 |
touchend | 结束 |
touchmove | 移动 |
特殊事件
名称 | 描述 |
---|---|
animationend | 动画结束 |
transitionend | 过度结束 |
表单事件
名称 | 描述 |
---|---|
submit | 只有提交表单时,触发的事件 |
focus | 标签获取焦点会处触发的事件 |
input | 输入数据时会触发的事件 |
change | 失去加并且输入数据改变是触发事件 |
浏览器兼容处理
1、浏览器滚动高度
1 2 | var height=document.documentElement.scrollTop||document.body.scrollTop var width=document.documentElement.scrollLeft||document.body.scrollLeft |
- 有文档类型声明
1 2 | document.documentElement.scrollTop document.documentElement.scrollLeft |
- 没有文档类型声明
1 2 | document.body.scrollTop document.body.scrollLeft |
2、获取非行内样式属性
实际效果是,获取标签执行的样式属性
1 2 3 4 5 | if (window.getComputedStyle){ window.getComponentStyle(dom).width } else { doc.currentStyle.width } |
3、获取事件对象
1 2 3 | dom.onclick= function (e){ e=e||window.event } |
4、获取事件对象目标
兼容低版本火狐浏览器,现在基本上不用了
1 2 3 4 | dom.事件= function (){ e=e||window.event var target=e.target||e.srcElement } |
5、按键数值
兼容低版本火狐浏览器,现在基本上不用了
1 2 3 4 | document.onkeyup=function(e){ e=e||window.event var keyNum=e.keyCode||e.which } |
6、事件的监听/事件的注册
1 2 3 4 5 6 7 8 | function myAddEvent(ele,type,fun){ 判断addEventListener这个方法是否存在 if(ele.addEventListener){ ele.addEventListener(type,fun) }else{ ele.attachEvent('on'+type,fun) } } |
7、删除事件处理函数
1 2 3 4 5 6 7 | function delFun(ele,type,fun){ if(ele.removeEventListener){ ele.removeEventListener(type,fun) }else{ ele.detachEvent('on'+type,fun) } } |
8、阻止事件传递
1 2 3 4 5 6 7 | function stopBBle(e){ if (e.stopPropagation){ e.stopPropagation() } else { e.cancelBubble= true } } |
9、阻止默认事件执行
1 2 3 4 5 | if (e.preventDefault){ e.preventDefault } else { e.returnValue= false } |
10、ajax对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | let xhr; try { //普通路蓝旗 xhr= new XMLHttpRequest() } catch (e){ //兼容IE低版本 xhr= new ActiveXObject( 'Microsoft.XMLHTTP' ) } xhr.open( 'post' , 'url' ) xhr.setRequestHeader( 'content-type' , 'application/x-www/form-url-encoded' ) xhr.send( 'name=111&age=222' ) //标准浏览器 xhr.onload = function (){} //兼容性写法 xhr.onreadystatechange= function (){ if (xhr.readystate==4){ let reg=/^a\d{2}$/ if (res.test(xhr.status)){ console.lof(json.parse(xhr.response)) } } } |
兼容性写法,封装工具
生成验证码函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function mySetVc() { var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXUZ' ; var newStr = '' ; for ( var i = 1; i <= 6; i++) { var num = parseInt(Math.random() * str.length) if (newStr.indexOf(str[num]) === -1) { newStr += str[num]; } else { i--; } } return newStr; } |
获取地址栏数据信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function getUrlVal() { // 1,获取地址栏参数字符串 let str = decodeURI(window.location.search).substr(1); // 创建存储结果的对象 let obj = {}; // 2 转化为数组 根据 分号空格转化 const arr1 = str.split( '&' ) // 3 循环变量数组,将数据字符串,根据=等号分割为数组 arr1.forEach(v => { let arr2 = v.split( '=' ); obj[arr2[0]] = arr2[1]; }) return obj; } |
生成table表格函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 参数1:数组,需要参照的数据数组 // 参数2:标签,需要写入内容的标签对象 function mySetTable(array, element) { var str = '' ; array.forEach( function (v, k) { str += '<tr>' ; for ( var key in v) { str += `<td>${v[key]}</td>`; } str += `<td><button index= "${k}" >删除</button></td>` str += '</tr>' ; }); element.innerHTML = str; var oBtns = document.querySelectorAll( 'button' ); mySetButton(oBtns, array, element); } |
给button按钮绑定删除效果函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // 参数1,button按钮数组 // 参数2,数据数组 // 参数3,写入内容的标签对象 function mySetButton(BtnArray, array, element) { BtnArray.forEach( function (v) { v.onclick = function () { var bool = window.confirm( '确定,是否删除' ); if (bool) { var index = v.getAttribute( 'index' ); array.splice(index, 1); mySetTable(array, element); } } }) } |
处理监听事件兼容性函数
1 2 3 4 5 6 7 8 9 10 11 12 | // 参数1:需要绑定事件的标签对象 // 参数2:需要绑定的事件类型,没有on // 参数3:需要绑定的事件处理函数 function myAddEvent(element, type, fun) { if (element.addEventListener) { // 普通浏览器 element.addEventListener(type, fun); } else { // 低版本IE浏览器 element.attachEvent( 'on' + type, fun); } } |
获取css样式函数
1 2 3 4 5 6 7 8 9 10 | // 参数1,需要属性的标签对象 // 参数2,需要属性的属性名称 function myGetStyle(element, type) { if (window.getComputedStyle) { return window.getComputedStyle(element)[type]; } else { return element.currentStyle[type]; } } |
设定 cookie 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // 参数1: cookie 的键名 // 参数2: cookie 的键值 // 参数3: cookie 的时效(秒数) function mySetCookie(key, value, time) { // 1,获取当前的时间对象 const nowTime = new Date(); // 2,获取当前时间的时间戳 --- 单位是毫秒 let timeStamp = nowTime.getTime(); // 3,计算时间戳 当前时间戳 - 8小时 + 时效的时间(秒) // 获取带有时效的时间戳 是世界标准时间 let newTimeStamp = timeStamp - 8 * 60 * 60 * 1000 + time * 1000; // 4,将时间戳设定回时间对象 nowTime.setTime(newTimeStamp); // 5,兼容没有传第三个参数的情况 // 如果 time 是 undefined ,证明没有第三个参数,执行会话时效,赋值空字符串 // 如果 time 不是 undefined ,证明没有第三个参数,执行 nowTime 时间对象中的时间戳时效 let endTime = time === undefined ? '' : nowTime; // 6,设定cookie // 给cookie多设定一个属性,path=/ // 让www中的所有文件都可以使用设定的cookie document.cookie = `${key}=${value};expires=${endTime};path=/`; } |
获取 cookie 的具体数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function myGetCookie() { // 创建存储结果的对象 let obj = {}; // 1 获取cookie字符串 let str = document.cookie; // 2 转化为数组 根据 分号空格转化 const arr1 = str.split( '; ' ) // 3 循环变量数组,将数据字符串,根据=等号分割为数组 arr1.forEach(v => { let arr2 = v.split( '=' ); obj[arr2[0]] = arr2[1]; }) return obj; } function fun(){ console.log( '我是新建的js文件中的内容,你压缩我了吗?' ) } |
到此这篇关于JavaScript中BOM和DOM详解的文章就介绍到这了,更多相关js BOM和DOM内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/221030/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)