JavaScript中BOM和DOM詳解
目錄
- BOM(瀏覽器物件模型)
- 1. window 獲取瀏覽器c視窗尺寸
- 2. screen 獲取電腦螢幕大小
- 3. window 開啟關閉視窗
- 4. 瀏覽器事件
- 5. location
- 6. history
- 7. navigator 獲取瀏覽器相關資訊
- 8. 彈窗
- DOM (文件物件模型)
- DOM 分類
- DOM物件
- Document文件物件
- element文件物件
- DOM事件操作
- 滑鼠事件
- 鍵盤事件
- 觸屏事件
- 特殊事件
- 表單事件
- 瀏覽器相容處理
- 相容性寫法,封裝工具
BOM(瀏覽器物件模型)
所有瀏覽器都支援window物件,他表示瀏覽器視窗。
所有全域性物件,函式,變數均自動成為window物件的成員。
全域性變數是window物件的屬性。全域性函式是window物件的方法。
基於html dom的document也是window物件的屬性之一。
window.document.getElementById("header"); document.getElementById("header");
1. window 獲取瀏覽器c視窗尺寸
瀏覽器視窗的內部高度(不包括滾動條,選單欄,工具欄)
window.innerHeight window.innerWidth
適用於Internet Explorer 8、7、6、5瀏覽器的window如下:
document.documentElement.clientHeight document.documentElement.clientWidth
相容方案獲取瀏覽器寬高`
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()
<script type="text/"> var newWindows; function newWindow() { newWindows = window.open("https://www.baidu.com/","baidu"); } 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引數 |
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 |
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 = ["","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,使用 Script訪問 HTML 文件的所有元素。
當被載入時,瀏覽器會建立頁面的文件物件模型
DOM 分類
定義了訪問和操作 HTML 文件的標準方法。DOM 將 HTML 文件表達為樹結構
html中,一切都是節點
- 元素節點
- 文字節點
- 屬性節點
各個節點關係為:父子關係\兄弟關係
通過可的物件模型,JavaScript 獲得了足夠的能力來建立動態的 HTML
- JavaScript 能夠改變頁面中的所有 HTML 元素。
- JavaScript 能夠改變頁面中的所有 HTML 屬性。
- JavaScript 能夠改變頁面中的所有 樣式。
- 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() | 通過標籤獲取相關元素陣列 不能SKGlAlz使用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 |
styhttp://www.cppcns.comle | 樣式 |
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、瀏覽器滾動高度
var height=document.documentElement.scrollTop||document.body.scrollTop var width=document.documentElement.scrollLeft||document.body.scrollLeft
- 有文件型別宣告
document.documentElement.scrollTop document.documentElement.scrollLeft
- 沒有文件型別宣告
document.body.scrollTop document.body.scrollLeft
2、獲取非行內樣式屬性
實際效果是,獲取標籤執行的樣式屬性
if(window.getComputedStyle){ window.getComponentStyle(dom).width }else{ doc.currentStyle.width }
3、獲取事件物件
dom.onclick=function(e){ e=e||window.event }
4、獲取事件物件目標
相容低版本火狐瀏覽器,現在基本上不用了
dom.事件=function(){ e=e||window.event var target=e.target||e.srcElement }
5、按鍵數值
相容低版本火狐瀏覽器,現在基本上不用了
document.onkeyup=function(e){ e=e||window.event var keyNum=e.keyCode||e.which }
6、事件的監聽/事件的註冊
function myAddEvent(ele,type,fun){ 判斷addEventListener這個方法是否存在 if(ele.addEventListener){ ele.addEventListener(type,fun) }else{ ele.attachEvent('on'+type,fun) } }
7、刪除事件處理函式
function delFun(ele,fun){ if(ele.removeEventListener){ ele.removeEventListener(type,fun) }else{ ele.detachEvent('on'+type,fun) } }
8、阻止事件傳遞
function stopBBle(e){ if(e.stopPropagation){ e.stopPropagation() }else{ e.cancelBubble=true } }
9、阻止預設事件執行
if(e.preventDefault){ e.preventDefault }else{ e.returnValue=false }
10、ajax物件
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)) } } }
相容性寫法,封裝工具
生成驗證碼函式
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; }
獲取位址列資料資訊
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:標籤,需要寫入內容的標籤物件 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,button按鈕陣列 // 引數2,資料陣列 // 引數3,寫入內容的標籤物件 function mySetButton(BtnArray,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:需要繫結的事件型別,沒有on // 引數3:需要繫結的事件處理函式 function myAddEvent(element,fun) { if (element.addEventListener) { // 普通瀏覽器 http://www.cppcns.com element.addEventListener(type,fun); } else { // 低版本IE瀏覽器 element.attachEvent('on' + type,fun); } }
獲取css樣式函式
// 引數1,需要屬性的標籤物件 // 引數2,需要屬性的屬性名稱 function myGetStyle(element,type) { if (window.getComputedStyle) { return window.getComputedStyle(element)[type]; } else { return element.currentStyle[type]; } }
設定 cookie 函式
// 引數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 的具體資料
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內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!