BOM 和 DOM
文章目錄
- BOM 和 DOM
- 一、介紹
- BOM結構圖
- 二、BOM
- 1. window物件
- 2. window的子物件
- 2.1 navigator物件
- 2.2 history物件
- 2.3 location物件(掌握)
- 2.4 彈出框
- 2.5 定時器
- 3.小結
- 4.練習
- 三、DOM
- 1. 查找標簽之直接查找
- 總結:
- 2.間接查找
- 代碼示例:
- 3.節點操作
- 總結:
- 4.獲取值操作
- 5.class、css操作
- 6.事件
- 6.1 什么是事件?
- 6.2 常用事件
- 6.3 事件之匯入js的2種方式 和 系結事件的2種方式
- 6.4 事件之onclick實體: 開關燈
- 6.5 事件之onfoucs+onblur實體: input框
- 6.6 事件之onclick+定時器實體: 展示當前時間
- 6.7 事件之onchange實體: 省市聯動
- 7.練習
- 四、總結:
一、介紹
到目前為止,我們已經學過了JavaScript的一些簡單的語法,但是這些簡單的語法,并沒有和瀏覽器有任何互動,
也就是我們還不能制作一些我們經常看到的網頁的一些互動,我們需要繼續學習BOM和DOM相關知識,
JavaScript分為 ECMAScript,DOM,BOM,
BOM(Browser Object Model)是指瀏覽器物件模型 ,作用是通過js代碼操作瀏覽器
DOM ( Document Object Model)是指檔案物件模型,作用是通過js代碼操作標簽,通過它訪問HTML檔案的所有元素,
Window物件是客戶端JavaScript最高層物件之一,由于window物件是其它大部分物件的共同祖先,在呼叫window物件的方法和屬性時,可以省略window物件的參考,例如:window.document.write()可以簡寫成:document.write(),
BOM結構圖

從上圖可以看出來:
- DOM物件也是BOM的一部分
- window物件是BOM的頂層(核心)物件
window物件是BOM的頂層(核心)物件
#1、在呼叫window物件的方法和屬性時,可以省略window,例如:window.document.location可以簡寫為document.location
#2、全域變數也是windows物件的屬性,全域的函式時window物件的方法
二、BOM
1. window物件
window物件指代的就是瀏覽器視窗
console.log(window.innerHeight); // 927 (瀏覽器視窗內的高度)
console.log(window.innerWidth); // 1918 (瀏覽器視窗內的寬度)
// window.open('https://www.baidu.com', '', 'height=400px, width=400px, top=400px, left=400px'); // 新建視窗打開頁面 第二個引數寫空即可 第三個引數寫新建的視窗的大小和位置
// window.close(); // 關閉當前頁面
// window.opener(); // 擴展父子頁面通信(了解)
// 總結
/*
window.innerHeight(); 瀏覽器內部高度
window.innerWidth(); 瀏覽器內部寬度
window.open(url, '', '寬高+位置');
window.close(); 關閉當前頁面
window.opener();
*/
2. window的子物件
提示: 如果是window的子物件 那么window可以省略不寫, 下面寫是為了更加見名知意.
2.1 navigator物件
console.log(window.navigator.appName); // Netscape (瀏覽器名稱)
console.log(window.navigator.appVersion); // 5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 (回傳瀏覽器版本)
console.log(window.navigator.userAgent); // Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 (掌握: 決議出用戶資訊)
// 擴展:仿爬措施
/*
1.最簡單最常用的一個就是校驗當前請求的發起者是否是一個瀏覽器
userAgent
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
如何破解該措施
在你的代碼中加上上面的user-agent配置即可
*/
console.log(window.navigator.platform); // Win32 (平臺)
// 總結
/*
window.navigator.appName; 瀏覽器名稱
window.navigator.appVersion; 回傳瀏覽器版本
window.navigator.userAgent; 決議出用戶資訊
window.navigator.platform; 平臺
*/
2.2 history物件
// 對應的就是你瀏覽器左上方的兩個的箭頭
window.history.back(); // 回退到上一頁
window.history.forward(); // 前進到下一頁
2.3 location物件(掌握)
// 一. location物件的瀏覽器的位置操作
// 1. href屬性: 獲取url地址欄的,整個url(統一資源定位器)
console.log(location.href);
// 2. host屬性: 獲取url地址欄的,IP和埠號
console.log(location.host);
// 3. hostname屬性: 獲取url地址欄的,IP
console.log(location.hostname);
// 4. port屬性: 獲取url地址欄的,埠號
console.log(location.port);
// 5. protocol屬性: 獲取url地址欄的,協議名稱
console.log(location.protocol);
// 6. search屬性: 獲取url地址欄的,?后面查詢的內容
console.log(location.search);
// 7. pathname屬性: 獲取url地址欄的,html檔案路徑地址
console.log(location.pathname);
// 二. location物件的瀏覽器的位置操作
// 1. location.href = 'url', 當前頁面跳轉新的網址,保留歷史記錄
location.href = 'https://www.baidu.com';
// 2. location.replace('url'), 當前頁面跳轉新的網址,不保留歷史記錄
location.replace('https://www.baidu.com');
// 3. location.reload(), 多載當前網頁(用的少)
location.reload();
2.4 彈出框
alert('警告框');
console.log(confirm('確認框')); // 回傳布林值
console.log(prompt('提示框')); // 回傳輸入值
2.5 定時器
function func1() {
alert('111');
}
let t1 = setTimeout(func1, 3000); // 毫秒為單位 3秒之后自動執行func1函式
// clearTimeout(t1); // 取消定時任務 如果你想要清除定時任務 需要提前前用變數(t1)指代定時任務
// cleatTimeout(setTimeout(func1, 3000)); // 簡寫
function func2() {
alert('222');
}
function show() {
let t2 = setInterval(func2, 3000);
function inner() {
clearInterval(t2);
}
setTimeout(inner, 9000); // 9秒中之后觸發inner清除定時器t2
}
show();
// 總結:
/*
一次性定時器:
let t = setTimeout(func, 毫秒);
clearTimeout(t);
多次性定時器:
function show() {
let t = setInterval(func, 毫秒);
function inner() {
clearInterval(t);
}
setTimeout(inner, 毫秒);
}
*/
3.小結
Browser Object Model
window物件
innerHeight; 瀏覽器內高
innerWidth; 瀏覽器內寬
open(url, '', '寬高+位置');
close();
window子物件:
navigator
navigator.appName; 瀏覽器名
navigator.appVersion; 瀏覽器版本
navigator.userAgent; 決議用戶資訊
navigator.platform; 平臺
history:
history.back(); 回退
history.forward(); 前進
location:
location.href 獲取url
location.href=url 跳轉url
location.reload 多載
彈出框:
警告框: alert(value);
確認框: confirm(value); 回傳布爾
提示框: prompt(value); 回傳輸入內容
定時器:
一次性:
let t = setTimeout(func, 3000);
clearTimeout(t);
多次性:
function show() {
let t = setInterval(func, 3000);
function inner() {
clearInterval(t);
}
setTimeout(inner, 9000);
}
4.練習
練習:上一頁下一頁
================page11.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>第一個頁</p>
<a href="page22.html">點我進入下一頁</a>
</body>
</html>
================page22.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>第二個頁</p>
<a href="page33.html">點我進入下一頁</a>
</body>
</html>
================page33.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function back() {
window.history.back()
}
</script>
</head>
<body>
<p>第三個頁</p>
<input type="button" value="點我進入上一頁" onclick="back()">
</body>
</html>
location.href練習2:3s后,自動跳轉頁面
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>這天下,本就是大爭之世,孤的兒子,不僅要爭,而且要爭的光芒萬丈</div>
<script>
setTimeout(function () {
location.href = 'https://www.cnblogs.com/linhaifeng';
}, 3000)
</script>
</body>
</html>
location.href練習3:3s后讓網頁整個重繪
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>這天下,本就是大爭之世,孤的兒子,不僅要爭,而且要爭的光芒萬丈</div>
<script>
setTimeout(function () {
location.reload();
}, 3000)
</script>
</body>
</html>
三、DOM
DOM(Document Object Model)是一套對檔案的內容進行抽象和概念化的方法,
當網頁被加載時,瀏覽器會創建頁面的檔案物件模型(Document Object Model),DOM標準規定HTML檔案中的每個成員都是一個節點(node)
HTML DOM 模型被構造為物件的樹,HTML DOM樹如下圖:

"""
DOM樹的概念
所有的標簽都可以稱之為是節點
JavaScript 可以通過DOM創建動態的 HTML:
JavaScript 能夠改變頁面中的所有 HTML 元素
JavaScript 能夠改變頁面中的所有 HTML 屬性
JavaScript 能夠改變頁面中的所有 CSS 樣式
JavaScript 能夠對頁面中的所有事件做出反應
DOM操作操作的是標簽 而一個html頁面上的標簽有很多
1.先學如何查找標簽
2.再學DOM操作標簽
DOM操作需要用關鍵字document起手
"""
1. 查找標簽之直接查找
三種查找標簽方法: id查找, 類查找, 標簽查找
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>div上面的div</div>
<div>div上面的div</div>
<div id="d1">div
<div>div>div</div>
<p>div>p
<span class="c1">div>p>span
<span>div>p>span>span</span>
</span>
<span class="c1">div>p>span+span</span>
</p>
<p>div>p</p>
</div>
<div>div下面的div</div>
<div>div下面的div</div>
<script>
// 三種查找標簽方法: id查找, 類查找, 標簽查找
/*直接查找*/
let divEle = document.getElementById('d1');
console.log(divEle); // 回傳#d1自己+所有后代元素
/*
<div id="d1">div
<div>div>div</div>
<p>div>p
<span class="c1">div>p>span</span>
</p>
<p>div>p</p>
</div>
*/
let spanEle = document.getElementsByClassName('c1');
console.log(spanEle); // 回傳所有的.c1(陣列)
/*
HTMLCollection [span.c1]
0: span.c1
length: 1
__proto__: HTMLCollection
*/
console.log(spanEle[0]);
/*
<span class="c1">div>p>span
<span>div>p>span>span</span>
</span>
*/
let pEle = document.getElementsByTagName('p');
console.log(pEle); // 回傳所有的p(陣列)
/*
HTMLCollection(2) [p, p]
0: p
1: p
length: 2
__proto__: HTMLCollection
*/
console.log(pEle[0]);
/*
<p>div>p
<span class="c1">div>p>span
<span>div>p>span>span</span>
</span>
<span class="c1">div>p>span+span</span>
</p>
*/
</script>
</body>
</html>
總結:
id查找 document.getElementById();
回傳物件. 可以拿到自己+后代所有
類查找 document.getElementsByClassName();
回傳陣列物件. 通過索引取值可以拿到自己+后代所有
元素查找 document.getElementsByTagName();
回傳陣列物件. 通過索引取值可以拿到自己+后代所有
2.間接查找
| 語法 | 含義 |
|---|---|
| childNodes | 獲取所有的子節點,除了元素還有文本等 |
| children | 獲取所有元素子節點,不包含文本 |
| parentNode | 獲取父節點 |
| previousSibling | 獲取上一個兄弟節點,包含文本 |
| previousElementSibling | 獲取上一個兄弟元素節點,不包含文本 |
| nextSibling | 獲取下一個兄弟節點,包含文本 |
| nextElementSibling | 獲取下一個兄弟元素節點,不包含文本 |
| firstChild | 獲取第一個子節點,包含文本 |
| firstElementChild | 獲取第一個子節點,不包含文本 |
| lastChild | 獲取最后一個子節點,包含文本 |
| lastElementChild | 獲取父元素最后一個元素節點,不包含文本 |
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>div上面的div</div>
<div>div上面的div</div>
<div id="d1">div
<div>div>div</div>
<p>div>p
<span class="c1">div>p>span
<span>div>p>span>span</span>
</span>
<span class="c1">div>p>span+span</span>
</p>
<p>div>p</p>
</div>
<div>div下面的div</div>
<div>div下面的div</div>
<script>
/*間接查找*/
let divEle = document.getElementById('d1');
console.log(divEle.parentElement); // 拿父節點
console.log(divEle.parentElement.parentElement); // 拿父節點的父節點
console.log(divEle.parentElement.parentElement.parentElement); // 拿父節點的拿父節點的拿父節點(沒有回傳null)
console.log(divEle.children); // 獲取所有的子標簽(回傳陣列物件)
console.log(divEle.children[0]); // 通過索引取值第一個子標簽
console.log(divEle.firstElementChild); // 與上面等同
console.log(divEle.children[divEle.children.length-1]); // 通過索引獲取最后一個子標簽
console.log(divEle.lastElementChild); // 與上面等同
console.log(divEle.nextElementSibling); // 同級別下面第一個
console.log(divEle.previousElementSibling); // 同級別上面第一個
// 總結
/*
注意: 下面所有拿到的標簽如果沒有后代標簽則就是單個. 如果有那么后代標簽物件也會被包含, 只是以當前拿到的標簽作為起始.
拿父標簽: 沒有父標簽回傳null
nodeEle.parentElement
拿所有子標簽: nodeEle.children
回傳所有子標簽, 以陣列的形式呈現. 可以通過索引取值獲取其內部的子標簽.
拿子標簽第一個:
nodeEle.firstElementChild
nodeEle.children[0]
拿子標簽最后一個:
nodeEle.lastElementChild
nodeEle.children[nodeEle.children.length-1]
拿同級別上一個:
nodeEle.nextElementSibling
拿同級別下一個:
nodeEle.previousElementSibling
*/
</script>
</body>
</html>
3.節點操作
涵蓋了: 創建標簽, 為創建的標簽添加屬性, 為創建的標簽添加文本, 對創建的標簽進行追加, 對創建的標簽進行插入.
以及補充的獲取標簽屬性, 洗掉標簽屬性. 洗掉標簽, 替換標簽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="d1">
<p id="d2">div>p</p>
<span>div>span</span>
</div>
<script>
/*
通過DOM操作動態的創建img標簽
并且給標簽加屬性
最后將標簽添加到文本中
*/
/*創建標簽*/
let imgEle = document.createElement('img'); // 創建標簽
imgEle.src = 'https://img2020.cnblogs.com/blog/1402974/202005/1402974-20200518221931333-1731690860.png'; // 給標簽設定默認的屬性
imgEle.useranme = 'jsaon'; // 自定義的屬性沒辦法點的方式直接設定
console.log(imgEle);
/*
<img src="https://img2020.cnblogs.com/blog/1402974/202005/1402974-20200518221931333-1731690860.png">
*/
imgEle.setAttribute('username', 'jsaon'); // 既可以設定自定義的屬性也可以設定默認的書寫
console.log(imgEle);
/*
<img src="https://img2020.cnblogs.com/blog/1402974/202005/1402974-20200518221931333-1731690860.png" username="jsaon">
*/
/*標簽內部添加元素*/
let divEle = document.getElementById('d1');
divEle.appendChild(imgEle); // 尾部追加
console.log(divEle);
/*
<div id="d1">
<p id="d2">div>p</p>
<span>div>span</span>
<img src="https://img2020.cnblogs.com/blog/1402974/202005/1402974-20200518221931333-1731690860.png" username="jsaon">
</div>
*/
/*
創建a標簽
設定屬性
設定文本
添加到標簽內部
添加到指定的標簽的上面
*/
let aEle = document.createElement('a'); // 創建a標簽
aEle.href = 'https://www.baidu.com'; // 設定屬性
aEle.innerText = '點我有你好看!'; // 給標簽設定文本內容
// let divEle = document.getElementById('d1');
let pEle = divEle.firstElementChild;
// let pEle = document.getElementById('d2');
divEle.insertBefore(aEle, pEle); // 添加標簽內容指定位置添加
console.log(divEle);
/*
<div id="d1">
<a href="https://www.baidu.com">點我有你好看!</a><p id="d2">div>p</p>
<span>div>span</span>
<img src="https://img2020.cnblogs.com/blog/1402974/202005/1402974-20200518221931333-1731690860.png" username="jsaon">
</div>
*/
// innerText與innerHTML
// let divEle = document.getElementById('d1');
console.log(divEle.innerText); // 獲取標簽內部所有的文本
/*
點我有你好看!
div>p
div>span
*/
console.log(divEle.innerHTML); // 內部文本和標簽都拿到
/*
點我有你好看!
div>p
div>span
<a href="https://www.baidu.com">點我有你好看!</a><p id="d2">div>p</p>
<span>div>span</span>
<img src="https://img2020.cnblogs.com/blog/1402974/202005/1402974-20200518221931333-1731690860.png" username="jsaon">
*/
divEle.innerText = '哈哈哈';
console.log(divEle.innerText); // 哈哈哈
divEle.innerHTML = '嘻嘻嘻';
console.log(divEle.innerHTML); // 嘻嘻嘻
divEle.innerText = '<h1>哈哈哈</h1>'; // 不識別html標簽
console.log(divEle.innerText); // <h1>哈哈哈</h1>
divEle.innerHTML = '<h1>嘻嘻嘻</h1>'; // 識別html標簽
console.log(divEle.innerText); // 嘻嘻嘻
// 額外補充
/*
appendChild()
removeChild()
replaceChild()
setAttribute() 設定屬性
getAttribute() 獲取屬性
removeAttribute() 移除屬性
*/
</script>
</body>
</html>
總結:
創建標簽: let imgEle = document.createElement('img');
設定屬性:
只能設定內置屬性: imgEle.src='';
內置屬性+自定義屬性: imgEle.setAttribute('username', 'jason');
追加標簽:
let divEle = document.getElementById('d1');
divEle.appendChild(imgEle);
插入標簽:
let divEle = document.getElementById('d1');
let pEle = divEle.firstElementChild();
let aEle = document.creatElement('a');
divEle.insertBefore(aEle, pEle) // 將aEle插入到divEle中的第一個子標簽pEle之前.(第一個引數始是要插入的元素, 第二個引數是插入的位置. 還需要明確是在那個標簽中插.)
innerText 和 innerHTML
訪問內容:
訪問內容所有文本: divEle.innerText
訪問內容所有文本+標簽: divEle.innerHTML
設定內容:
let aEle = document.createElement('a');
只設定文本內容:
aEle.innerText = '哈哈哈';
文本內容+標簽:
aEle.innerHTML = '<h1>哈哈哈</h1>';
4.獲取值操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="d1" value="111">
<select name="" id="d2">
<option value="haha" selected>哈哈</option>
<option value="heihei">嘿嘿</option>
<option value="momo">摸摸</option>
</select>
<input type="file" id="d3" multiple>
<script>
/*獲取用戶資料標簽內部的資料*/
var inputEle = document.getElementById('d1');
console.log(inputEle.value); // 111
var seEle = document.getElementById('d2');
console.log(seEle.value); // haha
var fileEle = document.getElementById('d3');
console.log(fileEle.value); // C:\fakepath\2sCode.zip (只能獲取到檔案的本地路徑, 無法獲取到檔案資料)
console.log(fileEle.files);
/*
FileList {0: File, 1: File, length: 2}
0: File {name: "2sCode.zip", lastModified: 1588031367082, lastModifiedDate: Tue Apr 28 2020 07:49:27 GMT+0800 (中國標準時間), webkitRelativePath: "", size: 8192, …}
1: File {name: "6組發布內容.txt", lastModified: 1587516178144, lastModifiedDate: Wed Apr 22 2020 08:42:58 GMT+0800 (中國標準時間), webkitRelativePath: "", size: 2553, …}
length: 2
__proto__: FileList
*/
console.log(fileEle.files[0]); // 獲取檔案資料
/*
File {name: "2sCode.zip", lastModified: 1588031367082, lastModifiedDate: Tue Apr 28 2020 07:49:27 GMT+0800 (中國標準時間), webkitRelativePath: "", size: 8192, …}
*/
// 總結:
/*
非檔案獲取值:
var inputEle = document.getElementById('d1');
inputEle.value
針對檔案:
var fileEle = document.getElementById('d3');
獲取本地上傳路徑: fileEle.value
獲取檔案物件們: fileEle.files
獲取檔案物件: fileEle.files[0]
補充: 如果想重置某標簽下的所有值使用inputEle.value='';
*/
</script>
</body>
</html>
5.class、css操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d1 {
height: 400px;
width: 400px;
border-radius: 50%;
}
.bg_green {
background-color: green;
}
.bg_red {
background-color: red;
}
</style>
</head>
<body>
<div id="d1" class="c1 bg_green bg_red"></div>
<p>呼呼哈哈哈哈哈哈</p>
<script>
let divEle = document.getElementById('d1');
console.log(divEle.classList); // 獲取標簽所有的類屬性
/*
DOMTokenList(3) ["c1", "bg_green", "bg_red", value: "c1 bg_green bg_red"]
0: "c1"
1: "bg_green"
length: 2
value: "c1 bg_green"
__proto__: DOMTokenList
*/
divEle.classList.remove('bg_red');
console.log(divEle.classList); // 移除某個類屬性
/*
DOMTokenList(2) ["c1", "bg_green", value: "c1 bg_green"]
0: "c1"
1: "bg_green"
length: 2
value: "c1 bg_green"
__proto__: DOMTokenList
*/
divEle.classList.add('bg_red');
console.log(divEle.classList); // 添加類屬性
/*
DOMTokenList(3) ["c1", "bg_green", "bg_red", value: "c1 bg_green bg_red"]
0: "c1"
1: "bg_green"
length: 2
value: "c1 bg_green"
__proto__: DOMTokenList
*/
console.log(divEle.classList.contains('c1')); // true
console.log(divEle.classList.contains('c99')); // false
console.log(divEle.classList.toggle('bg_red')); // false (有則洗掉無則添加. 執行之前是有的, 執行之后發現有就洗掉了, 所以列印是false)
// console.log(divEle.classList.toggle('bg_red')); // true
// console.log(divEle.classList.toggle('bg_red')); // false
// console.log(divEle.classList.toggle('bg_red')); // true
/*DOM操作操作標簽樣式 統一先用style起手*/
let pEle = document.getElementsByTagName('p')[0];
pEle.style.color = 'red';
pEle.style.fontSize = '28px';
pEle.style.backgroundColor = 'yellow';
pEle.style.border = '3px solid red';
// 總結:
/*
屬性操作:
獲取標簽所有類屬性 divEle.classList; --> 回傳陣列物件
獲取標簽所有類屬性中的某個屬性: divEle.classList[0];
洗掉獲取的標簽所有類屬性中的某個屬性: divEle.classList.remove('bg_red');
往獲取的標簽所有類屬性中添加某個屬性: divEle.classList.add('bg_red');
對獲取的標簽所有類屬性中判斷某個屬性是否存在: divEle.classList.contains('c1'); --> 回傳布林值
對獲取的標簽所有類屬性中如果屬性存在則洗掉,不存在則添加: divEle.classList.toggle('bg_red'); --> 之前有布林值為true, 執行了以后洗掉了它, 布林值就是false
樣式設定:
pEle.style.屬性名 = 屬性值;
*/
</script>
</body>
</html>
6.事件
6.1 什么是事件?
事件就是達到某一特定的條件自動觸發的某種功能
HTML 4.0 的新特性之一是有能力使 HTML 事件觸發瀏覽器中的動作(action),比如當用戶點擊某個 HTML 元素時執行一段JavaScript,下面是一個屬性串列,這些屬性可插入 HTML 標簽來定義事件動作,
6.2 常用事件
onclick 滑鼠單擊
ondblclick 雙擊后激活事件
onfocus 獲得焦點時觸發
onblur 失去焦點時觸發 應用場景:用于表單驗證,用戶離開某個輸入框時,代表已經輸入完了,我們可以對它進行驗證.
onchange 域的內容被改變, 應用場景:通常用于表單元素,當元素內容被改變時觸發.(select聯動)
onkeydown 某個鍵盤按鍵被按下, 應用場景: 當用戶在最后一個輸入框按下回車按鍵時,表單提交
onkeypress 某個鍵盤按鍵被按下并松開,
onkeyup 某個鍵盤按鍵被松開,
onload 載入網頁時
onmousedown 滑鼠按鈕被按下,
onmousemove 滑鼠被移動,
onmouseout 滑鼠從某元素移開,
onmouseover 滑鼠移到某元素之上,
onselect 在文本框中的文本被選中時發生,
onsubmit 確認按鈕被點擊,使用的物件是form,
6.3 事件之匯入js的2種方式 和 系結事件的2種方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
/*匯入js的第二種方式實作: 使用window.onload預加載, 等待以下標簽都加載完畢以后才執行以下代碼*/
// 注意: onl oad事件只能宣告一個,宣告多個會出現事件覆寫現象,下面的定義的事件覆寫上面的事件
window.onload = function () {
// 第一種系結事件的方式: 這種方式的缺點就是無法執行οnclick="func1()"這種系結方式, 所以還是推薦使用第一種方式將js代碼寫在body標簽底部
function func1() {
prompt('提示框');
}
// 第二種系結事件的方式:: 推薦
let btnEle = document.getElementById('d1');
btnEle.onclick = function () {
confirm(navigator.userAgent);
}
}
</script>
</head>
<body>
<button onclick="func1()">點我</button>
<button id="d1">點我</button>
<script>
/*匯入js的第一種方式實作: 在以上標簽都加載完畢以后才執行以下代碼*/
// function func1() {
// prompt('提示框');
// }
//
//
// let btnEle = document.getElementById('d1');
// btnEle.onclick = function () {
// confirm(navigator.userAgent);
// }
</script>
</body>
</html>
6.4 事件之onclick實體: 開關燈
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d1 {
height: 400px;
width: 400px;
border-radius: 50%;
}
.bg_green {
background-color: green;
}
.bg_red {
background-color: red;
}
</style>
</head>
<body>
<div id="d1" class="c1 bg_red bg_green"></div>
<button id="d2">變色</button>
<script>
// onclick: 滑鼠單擊觸發
let divEle = document.getElementById('d1');
let btnEle = document.getElementById('d2');
btnEle.onclick = function () {
divEle.classList.toggle('bg_red');
};
</script>
</body>
</html>
6.5 事件之onfoucs+onblur實體: input框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" value="老板去嗎?" id="d1">
<script>
/*
onfocus: 獲得焦點時觸發
onblur: 失去焦點時觸發. 應用場景:用于表單驗證,用戶離開某個輸入框時,代表已經輸入完了,我們可以對它進行驗證.
*/
/*
解題思路:
1. 當滑鼠獲取inputEle焦點時, 內容被清空
2. 當滑鼠移開inputEle焦點時, 內容又展示
*/
let inputEle = document.getElementById('d1');
inputEle.onfocus = function () {
inputEle.value=''; // 點value就是獲取 等號賦值就是設定
};
inputEle.onblur = function () {
inputEle.value='不去, 沒錢!'; // 給input標簽重寫賦值
};
</script>
</body>
</html>
6.6 事件之onclick+定時器實體: 展示當前時間
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="d1">
<button id="d2">開始</button>
<button id="d3">結束</button>
<script>
let t; // 3. 那么定義一個全域存盤定時器的變數, 提供清除定時器能夠訪問到這個變數
let inputEle = document.getElementById('d1');
let startBtnEle = document.getElementById('d2');
let endBtnEle = document.getElementById('d3');
function showTime() {
let currentTime = new Date();
inputEle.value = currentTime.toLocaleString();
}
startBtnEle.onclick = function () {
if (!t) { // 2. 所以限制定時器只能開一個
t = setInterval(showTime, 1000); // 1. 每點擊一次就會開設一個定時器 而t只指代最后一個
}
};
endBtnEle.onclick = function () {
clearInterval(t);
t = null; // 4. 清除完了定時器, 還應該將t重置為空, 如果不置位空, 下次點擊!t布林值位true
}
</script>
</body>
</html>
6.7 事件之onchange實體: 省市聯動
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<select name="" id="d1"></select>
<select name="" id="d2"></select>
<script>
// onchange: 文本域變化事件. 應用場景:通常用于表單元素,當元素內容被改變時觸發.
let proEle = document.getElementById('d1');
let cityEle = document.getElementById('d2');
let data = {
"河北省": ["廊坊", "邯鄲"],
"北京": ["朝陽區", "海淀區"],
"山東": ["威海市", "煙臺市"]
};
// 1. 為proEle和cityEle初始化提示option
proEle.innerHTML = "<option disabled selected>--請選擇省--</option>";
cityEle.innerHTML = '<option disabled selected>--請選擇市--</option>';
// 2. for回圈取值獲取省, 并將獲取到的省添加到proEle內
for (let key in data) {
let optEle = document.createElement('option');
optEle.value = key;
optEle.innerText = key;
proEle.appendChild(optEle);
}
// 3. 當proEle被改變了自動觸發系結的onchange事件, 準備為cityEle添加對應的市區提供選擇
proEle.onchange = function () {
cityEle.innerHTML = ''; // 關鍵: 一上來就清空市區optEle, 為了防止下面多次選擇觸發appendChild出現一直追加的情況.
let cityArray = data[proEle.value];
// 4. 回圈所有的市 渲染到第二個select中
// // 方法一: 使用for回圈. (提示: for回圈取值爭對陣列取出來的是索引. 爭對物件{}取出來的是key)
// for (let index in cityArray) {
// let optEle = document.createElement('option');
// optEle.value = cityArray[index];
// optEle.innerText = cityArray[index];
// cityEle.appendChild(optEle);
// }
// 方法二: 使用forEach
cityArray.forEach(function (city) {
let optEle = document.createElement('option');
optEle.value = city;
optEle.innerText = city;
cityEle.appendChild(optEle);
}, this);
};
</script>
</body>
</html>
7.練習
案例一:模態框
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
#bg {
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
}
#content {
position: relative;
top: 150px;
width: 400px;
height: 200px;
line-height: 200px;
text-align: center;
color: red;
background-color: white;
margin: 0 auto;
}
#cancel {
position: absolute;
top: 0;
right: 0;
color: white;
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
background-color: red;
}
</style>
</head>
<body>
<input type="button" value="彈出模態框" id="btn">
<script>
var oBtn = document.getElementById('btn');
var oDiv = document.createElement('div');
var oP = document.createElement('p');
var oSpan = document.createElement('span');
oDiv.id = 'bg';
oP.id = 'content';
oSpan.id = 'cancel';
oP.innerHTML = '彈出模態框';
oSpan.innerHTML = 'X';
oDiv.appendChild(oP);
oP.appendChild(oSpan);
oBtn.onclick = function () {
this.parentNode.replaceChild(oDiv, this);
};
oSpan.onclick =function () {
oDiv.parentNode.replaceChild(oBtn,oDiv);
}
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,body {
height: 100%;
}
#bg {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.3);
display: none;
}
#content {
position: absolute;
top: 100px;
left: 50%;
margin-left: -150px;
background-color: white;
width: 300px;
height: 200px;
}
#content p:nth-child(3) {
position: absolute;
top: 100px;
}
</style>
</head>
<body>
<input type="button" value="彈出" id="btn">
<div id="bg">
<div id="content">
<p>
<label for="inp-username">用戶名: </label><input type="text" name="username" id="inp-username">
</p>
<p>
<label for="inp-password">密碼: </label><input type="text" name="username" id="inp-password">
</p>
<p>
<input type="button" value="提交" >
<input type="button" value="取消" id="cancel">
</p>
</div>
</div>
<script>
var oBtn = document.getElementById('btn');
var oBg = document.getElementById('bg');
var oInpUsername=document.getElementById('inp-username');
var oInpPwd=document.getElementById('inp-password');
var oInp=document.getElementById('cancel');
oBtn.onclick=function () {
oBg.style.display='block';
}
oInp.onclick=function () {
oInpUsername.value='';
oInpPwd.value='';
oBg.style.display='none'
}
</script>
</body>
</html>
案例二:點擊有驚喜
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 200px;
height: 200px;
background: red;
text-align: center;
color: white;
line-height: 200px;
font-size: 23px;
font-weight: bold;
margin: 20px auto;
}
</style>
</head>
<body>
<div class="box">點擊有驚喜!!!</div>
<script>
var oBox = document.getElementsByClassName('box')[0];
//初始化點擊的次數,通過次數的增加來改變DOM的樣式
var a = 0;
oBox.onclick = function () {
a++;
console.log(a % 4);
if (a % 4 === 1) {
this.style.background = 'green';
this.innerText = '繼續點擊哦!!!';
} else if (a % 4 == 2) {
this.style.background = 'blue';
this.innerText = '騙你的,傻逼';
} else if (a % 4 == 3) {
this.style.background = 'transparent';
this.innerText = '';
} else {
this.style.background = 'red';
this.innerText = '點擊有驚喜!!!';
}
}
</script>
</body>
</html>
案例三:簡易評論板
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#comment {
background-color: #b0b0b0;
width: 500px;
}
#comment ul li {
list-style: none;
background-color: wheat;
border: 1px dashed #000;
margin: 0px 10px 10px;
word-break: break-all;
word-wrap: break-word;
}
</style>
</head>
<body>
<div id="comment">
<p>評論內容:</p>
</div>
<div id="box">
<p>留言內容:</p>
<textarea name="" id="content" cols="30" rows="10"></textarea>
<p>
<input type="button" value="提交" id="btn">
<input type="button" value="統計" id="calculate">
</p>
</div>
<script>
var comment = document.getElementById('comment');
var box = document.getElementById('box');
var submit = document.getElementById('submit');
var content = document.getElementById('content');
var btn = document.getElementById('btn');
var calculate=document.getElementById('calculate');
var ul = document.createElement('ul');
comment.appendChild(ul);
var count=0;
btn.onclick = function () {
var val = content.value;
if (val.length != 0) {
var date = new Date();
var subTime = date.toLocaleString();
var li = document.createElement('li');
var p1 = document.createElement('h3');
var p2 = document.createElement('p');
var spans = document.getElementsByClassName('del');
count=spans.length+1;
p1.innerHTML = '#'+'<span class="num">'+count+'</span>'+'樓'+' '+subTime + '<span class="del"> 洗掉</span>';
p2.innerHTML = val;
li.appendChild(p1);
li.appendChild(p2);
ul.appendChild(li);
content.value = '';
}
function aa() {
var spans = document.getElementsByClassName('del');
for (var i = 0; i < spans.length; i++) {
spans[i].onclick=function (currentIndex) {
function bb() {
ul.removeChild(this.parentNode.parentNode);
count--;
var ss=document.getElementsByClassName('num');
for (var j=currentIndex;j<ss.length;j++){
ss[j].innerHTML=parseInt(ss[j].innerHTML)-1;
}
aa();
}
return bb;
}(i);
}
}
aa()
};
calculate.onclick = function () {
alert('一共發布了'+count+'條評論');
}
</script>
</body>
</html>
案例四:選項卡
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.tab {
width: 480px;
height: 200px;
border: 1px solid red;
margin: 0 auto;
}
ul li {
list-style: none;
width: 160px;
height: 60px;
line-height: 60px;
text-align: center;
background-color: #b0b0b0;
float: left;
}
li.active {
background-color: #55BBBB;
}
p {
display: none;
height: 200px;
text-align: center;
line-height: 200px;
background-color: white;
}
p.active {
display: block;
}
</style>
</head>
<body>
<div class="tab">
<ul>
<li class="active">首頁</li>
<li>新聞</li>
<li>圖片</li>
</ul>
<p class="active">首頁內容</p>
<p>新聞內容</p>
<p>圖片內容</p>
</div>
<script>
var aLi=document.getElementsByTagName('li');
var aP=document.getElementsByTagName('p');
for (var i=0;i<aLi.length;i++){
aLi[i].index=i;
aLi[i].onclick=function () {
for (var j=0;j<aLi.length;j++){
aLi[j].className='';
aP[j].className='';
}
this.className='active';
aP[this.index].className='active';
}
}
</script>
</body>
</html>
案例五:仿淘寶搜索框
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#search {
position: relative;
}
input {
outline: none;
display: block;
border: 2px solid #f2a83c;
border-radius: 10px;
width: 490px;
height: 50px;
margin-top: 20px;
}
label {
position: absolute;
top: 20px;
left: 10px;
font-size: 8px;
color: gray;
}
</style>
</head>
<body>
<div id="search">
<input type="text" id="text">
<label for="text" id="msg">老男孩上海校區</label>
</div>
<script>
var txt = document.getElementById('text');
var msg = document.getElementById('msg');
//檢測用戶表單輸入的時候
txt.oninput = function () {
//控制元素顯示隱藏
if (this.value == '') {
msg.style.display = 'block';
} else {
msg.style.display = 'none';
}
}
</script>
</body>
</html>
案例六:獲取當前時間
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
setInterval(function () {
var date = new Date();
var y = date.getFullYear();
var m = date.getMonth();
var d = date.getDate();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
//今天是2018年2月23日 8:23:09
document.body.innerHTML = "今天是" + y + '年' + num(m + 1) + "月" + num(d) + "日" + num(h) + ":" + num(min) + ":" + num(s)
}, 1000)
function num(n) {
if (n < 10) {
return "0" + n;
}
return n
}
</script>
</body>
</html>
案例七:勻速運動
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: #FF0000;
position: absolute;
top: 50px;
left: 0px;
}
</style>
</head>
<body>
<div id="wrap">
<button id="btn1">前進</button>
<button id="btn2">后退</button>
<div class="box" id="box1">
</div>
</div>
<script>
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var box1 = document.getElementById('box1')
var count = 0;
var time1 = null;
var time2 = null;
btn1.onclick = function () {
clearInterval(time2);
time1 = setInterval(function () {
count += 10;
if (count > 1000) {
box1.style.left = '1000px';
box1.style.borderRadius = '50%';
clearInterval(time1);
} else {
box1.style.left = count + 'px';
box1.style.borderRadius = count / 2000 * 100 + '%';
}
}, 10)
};
btn2.onclick = function () {
clearInterval(time1);
time2 = setInterval(function () {
count -= 10;
if (count <= 0) {
box1.style.left = '0px';
box1.style.borderRadius = '';
clearInterval(time2);
} else {
box1.style.left = count + 'px';
box1.style.borderRadius = count / 2000 * 100 + '%';
;
}
}, 10)
}
</script>
</body>
</html>
案例八:5s后關閉廣告
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
img {
position: fixed;
width: 300px;
}
ul {
list-style: none;
}
#left {
left: 0;
}
#right {
right: 0;
}
ul li {
font-size: 25px;
}
</style>
</head>
<body>
<img src="images/1.jpg" id="left">
<img src="images/1.jpg" id="right">
<ul>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
<li>屠龍寶刀,點擊就送</li>
</ul>
<script>
window.onload = function () {
var left = document.getElementById('left');
var right = document.getElementById('right');
setTimeout(function () {
left.style.display = 'none';
right.style.display = 'none';
}, 5000)
}
</script>
</body>
</html>
案例九:小米滾動
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.wrap {
width: 512px;
height: 400px;
border: 3px solid #808080;
position: relative;
overflow: hidden;
margin: 100px auto;
}
.wrap span {
width: 100%;
height: 200px;
position: absolute;
background-color: transparent;
border: 1px solid #000;
}
.up {
top: 0;
}
.down {
bottom: 0;
}
img {
position: absolute;
top: 0;
left: 0;
height: 200px;
}
</style>
</head>
<body>
<div id="box" class="wrap">
<img src="images/mi.png" id="xiaomi">
<span class="up" id="picUp">11111</span>
<span class="down" id="picDown">22222</span>
</div>
<script>
var up = document.getElementById('picUp');
var down = document.getElementById('picDown');
var img = document.getElementById('xiaomi');
var count = 0;
var time = null;
//滑鼠移入的時候吧
up.onmouseover = function () {
//不管怎樣 上來先清定時器
clearInterval(time);
time = setInterval(function () {
count -= 3;
count >= -1070 ? img.style.top = count + 'px' : clearInterval(time);
}, 30)
};
down.onmouseover = function () {
clearInterval(time);
time = setInterval(function () {
count += 1;
count < 0 ? img.style.top = count + 'px' : clearInterval(time);
}, 30)
}
</script>
</body>
</html>
案例十:無縫輪播
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
ul {
list-style: none;
}
.box {
width: 600px;
height: 700px;
margin: 50px auto;
overflow: hidden;
position: relative;
border: 1px solid #000;
}
ul li {
float: left;
}
.box ul {
width: 500%;
position: absolute;
top: 0;
left: 0;
}
img {
width: 600px;
}
</style>
</head>
<body>
<div class="box">
<ul>
<li><img src="https://images2018.cnblogs.com/blog/1036857/201805/1036857-20180516225816920-580320384.jpg"/></li>
<li><img src="https://images2018.cnblogs.com/blog/1036857/201805/1036857-20180516225809591-1990809146.jpg"/></li>
<li><img src="https://images2018.cnblogs.com/blog/1036857/201805/1036857-20180516225724530-539090864.jpg"/></li>
<li><img src="https://images2018.cnblogs.com/blog/1036857/201805/1036857-20180516225751362-1832630751.jpg"/></li>
<li><img src="https://images2018.cnblogs.com/blog/1036857/201805/1036857-20180516225816920-580320384.jpg"/></li>
</ul>
</div>
<script>
var box = document.getElementsByClassName('box')[0];
var ul = box.children[0];
var num = 0;
var timer = null;
timer = setInterval(autoPlay, 3);
//函式的宣告
function autoPlay() {
num--;
num <= -2400? num = 0: num;
ul.style.left = num + 'px'
}
//滑鼠移動上去
box.onmouseover = function () {
clearInterval(timer)
};
box.onmouseout = function () {
timer = setInterval(autoPlay, 3);
}
</script>
</body>
</html>
案例十一:用戶名和密碼校驗
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
span {
background-color: red;
}
</style>
</head>
<body>
<form>
<p>
<input type="text" name="username">
<span></span>
</p>
<p>
<input type="password" name="password">
<span></span>
</p>
<p>
<input type="button" value="提交" id="btn">
</p>
</form>
<script>
var isOk1=false
var reg1=new RegExp('(?!^[0-9]+$)(?!^[a-zA-Z]+$)^[0-9A-Za-z]{4}$')
var inp1 = document.getElementsByName("username")[0]
inp1.onblur=function () {
var res=reg1.test(this.value)
this.style.border="1px solid red"
if (!res) {
this.nextElementSibling.innerText="用戶名必須由4位字母和數字組成"
setTimeout(function () {
inp1.nextElementSibling.innerText=""
inp1.value=""
},3000)
}else {
this.style.border="1px solid green"
isOk1=true
}
}
var isOk2=false
var reg2=new RegExp('(?!^[0-9]+$)(?!^[a-zA-Z]+$)^[0-9A-Za-z]{6}$')
var inp2 = document.getElementsByName("password")[0]
inp2.onblur=function () {
var res=reg2.test(this.value)
this.style.border="1px solid red"
if (!res) {
this.nextElementSibling.innerText="密碼必須由6位字母和數字組成"
setTimeout(function () {
inp2.nextElementSibling.innerText=""
inp2.value=""
},3000)
}else {
this.style.border="1px solid green"
isOk2=true
}
}
var btn=document.getElementById("btn")
btn.onclick=function () {
if(isOk1 && isOk2) {
alert("提交成功")
}else {
alert("請重新填寫")
}
}
</script>
</body>
</html>
四、總結:
/*
查找標簽:
直接查找:
id查找 document.getElementById() 回傳物件
類名查找 document.getElementsByClassName() 回傳陣列物件
標簽名查找 document.getElementByTagName() 回傳陣列物件
間接查找:
查找父標簽: 沒有父標簽則回傳null
divEle.parentElement
查找所有子標簽: 回傳陣列物件, 通過索引取值獲取對應子標簽
divEle.children
查找第一個子標簽:
divEle.firstElementChild
divEle.children[0]
查找最后一個子標簽:
divEle.lastElementChild
divEle.children[divEle.children.length-1]
查找同級別上一個:
divEle.nextElementSibling
查找同級別下一個:
divEle.previousElementSibling
節點操作:
創建標簽:
let aEle = document.createElement('a');
添加屬性:
添加內置: aEle.alt='';
添加內置+自定義: aEle.setAttribute('username', 'egon');
拓展: getAttribute('username') removeAttribute('username')
文本操作:
獲取所有文本: aEle.innerText;
獲取所有文本+標簽: aEle.innerHTML;
添加文本: aEle.innerText='xxx';
添加文本+標簽: aEle.innerHTML='<h1>xxx</h1>;
追加標簽:
let divEle = document.getElementById('d1');
divEle.appendChild(aEle);
拓展: removeChild(aEle) replaceChild(src, dst)
插入標簽:
let pEle = divEle.children[0];
divEle.inertBefore(aEle, pEle)
獲取值操作:
獲取非檔案: inputEle.value
獲取檔案:
獲取檔案本次上傳路徑: inputEle.value
獲取檔案物件集合: inputEle.files 回傳格式{0: 檔案物件, 1: 檔案物件1}
獲取某一個檔案物件: inputEle.files[0]
拓展: 值清空
inputEle.value=''
class, css操作:
class操作:
獲取所有類屬性: divEle.classList 回傳陣列物件
獲取某一個類屬性: divEle.classList[0] 回傳陣列物件中按照索引取值的類名
對獲取到的所有類屬性進行追加: divEle.classList.add('bg_red')
對獲取到的所有類屬性進行洗掉: divEle.classList.remove('bg_red')
對獲取到的所有類屬性判斷是否存在某個類: divEle.classList.contains('bg_red') 回傳布林值
對獲取到的所有類屬性判斷有則洗掉,無則添加: divEle.classList.toggle('bg_red') 之前有布林值為true, 執行了以后洗掉了它, 布林值就是false
css操作: 統一style起手, 將css中的橫桿換成駝峰體
divEle.style.backgroundColor = 'red';
divEle.style.fontSize = '28px';
事件: 滿足某種條件自動觸發的功能
匯入js的2種方式:
head中系結預加載事件window.onload. 預加載無法執行以下的系結事件的第一種方式. 且不能多次宣告, 多次系結, 下面會覆寫上面
body中底部
系結事件的2種方式:
標簽中定義屬性οnclick='func()'
通過DOM操作獲取標簽物件, 再通過標簽物件系結事件. 例如: aEle.onclick = function () {}
onclick 滑鼠單擊事件.
實體1: 開關燈. 主要利用nodeEle.classList.toggle實作
實體2: 展示當前時間. 主要利用創建時間物件new Date() + 回圈定時器實作
onfocus 獲得焦點時觸發事件 + onblur 失去焦點時觸發事件.
實體: input框的焦點獲取與失去. 主要利用inputEle.value實作
onchange 文本域變化事件
實體: 省市聯動. 主要利用節點操(創建標簽, 為標簽添加屬性, 為標簽添加文本內容, 找到需要添加的位置添加)
常用事件總結:
onclick 滑鼠單擊
ondblclick 雙擊后激活事件
onfocus 獲得焦點時觸發
onblur 失去焦點時觸發 應用場景:用于表單驗證,用戶離開某個輸入框時,代表已經輸入完了,我們可以對它進行驗證.
onchange 域的內容被改變, 應用場景:通常用于表單元素,當元素內容被改變時觸發.(select聯動)
onkeydown 某個鍵盤按鍵被按下, 應用場景: 當用戶在最后一個輸入框按下回車按鍵時,表單提交
onkeypress 某個鍵盤按鍵被按下并松開,
onkeyup 某個鍵盤按鍵被松開,
onl oad 載入網頁時
onm ousedown 滑鼠按鈕被按下,
onm ousemove 滑鼠被移動,
onm ouseout 滑鼠從某元素移開,
onm ouseover 滑鼠移到某元素之上,
onselect 在文本框中的文本被選中時發生,
onsubmit 確認按鈕被點擊,使用的物件是form,
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/282633.html
標籤:其他
