BOM(瀏覽器對象模型)
所有瀏覽器都支持window對象,他表示瀏覽器窗口。
所有js全局對象,函數,變量均自動成為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/javascript">
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
獲取當前網頁地址,吧瀏覽器從定向到新的網頁(當前頁打開)可以不用寫window這個前綴
名稱 | 描述 |
---|---|
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 = ["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 中位於指定下標的節點 |
.classList.add() | 添加class |
.classList.remove() | 移除class |
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、瀏覽器滾動高度
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,type,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, 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:需要綁定的事件類型,沒有on
// 參數3:需要綁定的事件處理函數
function myAddEvent(element, type, fun) {
if (element.addEventListener) {
// 普通瀏覽器
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文件中的內容,你壓縮我了嗎?')
}