JavaScript DOM操作與事件處理方法
前言
本文將通過一系列代碼片段,深入探討如何使用JavaScript進(jìn)行DOM操作、事件處理以及獲取和設(shè)置元素屬性。這些示例涵蓋了從基礎(chǔ)到進(jìn)階的技術(shù)點(diǎn),幫助讀者更好地理解JavaScript在實(shí)際項(xiàng)目中的應(yīng)用。
1. 類名操作
代碼片段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.active {
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<input type="button" value="on|off">
<div id="box"></div>
<script>
//1. 獲取元素
var div = document.querySelector('#box');
var onoff = document.querySelector('input');
//2. 添加類名
div.className = 'pox';
div.classList.add('hehe'); //添加新類名
div.classList.add('haha');
div.classList.add('active');
//獲取所有類名
console.log(div.classList, div.classList.length);
//通過下標(biāo)獲取指定的類名
console.log(div.classList.item(2));
//3. 添加事件
onoff.onclick = function () {
div.classList.toggle('active');
}
//4. 刪除指定類名
div.classList.remove('hehe');
//5. 查看指定的類名是否存在
console.log(div.classList.contains('hehe'));
</script>
</body>
</html>
代碼解析
獲取元素:
var div = document.querySelector('#box');
var onoff = document.querySelector('input');使用querySelector方法獲取頁面中的<div>和<input>元素。
添加類名:
div.className = 'pox';
div.classList.add('hehe');
div.classList.add('haha');
div.classList.add('active');className屬性可以直接設(shè)置或獲取元素的類名。classList提供了一組便捷的方法來操作類名,如add、remove、toggle等。
獲取所有類名:
console.log(div.classList, div.classList.length); console.log(div.classList.item(2));
classList是一個(gè)DOMTokenList對象,可以通過length屬性獲取類名數(shù)量,通過item方法獲取指定索引的類名。
添加事件:
onoff.onclick = function () {
div.classList.toggle('active');
}toggle方法用于切換類名的存在狀態(tài)。如果類名存在則移除,不存在則添加。
刪除指定類名:
div.classList.remove('hehe');查看指定的類名是否存在:
console.log(div.classList.contains('hehe'));2. 屬性操作
代碼片段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box" title="標(biāo)題" data-id="sp1"></div>
<script>
//1. 獲取元素
var div = document.getElementById('box');
//2. 獲取屬性
console.log(div.id, div['title']);
//3. 獲取自定義屬性
console.log(div.getAttribute('data-id'));
//4. 設(shè)置自定義屬性
div.setAttribute('data-cartId', '999');
//5. 刪除自定義屬性
div.removeAttribute('data-id');
console.log(div.dataset.cartId);
div.id = '';
</script>
</body>
</html>
代碼解析
獲取元素:
var div = document.getElementById('box');獲取屬性:
console.log(div.id, div['title']);
可以直接通過屬性名訪問標(biāo)準(zhǔn)屬性,如id和title。
獲取自定義屬性:
console.log(div.getAttribute('data-id'));使用getAttribute方法獲取自定義屬性值。
設(shè)置自定義屬性:
div.setAttribute('data-cartId', '999');使用setAttribute方法設(shè)置自定義屬性值。
刪除自定義屬性:
div.removeAttribute('data-id');使用dataset訪問自定義屬性:
console.log(div.dataset.cartId);
dataset屬性提供了一種更方便的方式訪問帶有data-前綴的自定義屬性。
修改id屬性:
div.id = '';
3. 內(nèi)容操作
代碼片段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="">
<div id="box"></div>
<script>
//1. 獲取元素
var txt = document.querySelector('input');
var div = document.querySelector('#box');
//3. 添加內(nèi)容
txt.value = '姓名:';
div.innerHTML = '呵呵<i>嘿嘿</i>嘻嘻';
//2. 獲取元素中的內(nèi)容
console.log(txt.value);
console.log(div.innerHTML);
console.log(div.innerText);
</script>
</body>
</html>
代碼解析
獲取元素:
var txt = document.querySelector('input');
var div = document.querySelector('#box');添加內(nèi)容:
txt.value = '姓名:'; div.innerHTML = '呵呵<i>嘿嘿</i>嘻嘻';
value屬性用于設(shè)置或獲取表單元素的值。innerHTML屬性用于設(shè)置或獲取HTML內(nèi)容,支持HTML標(biāo)簽解析。
獲取元素中的內(nèi)容:
console.log(txt.value); console.log(div.innerHTML); console.log(div.innerText);
innerText屬性僅獲取文本內(nèi)容,不包含HTML標(biāo)簽。
4. 尺寸和位置
代碼片段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 100px;
height: 100px;
background: red;
border: 1px solid black;
padding: 5px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
//1. 獲取元素
var div = document.querySelector('#box');
//2. 獲取div的相對寬高
console.log(div.offsetWidth, div.offsetHeight); //112 112
console.log(div.clientWidth, div.clientHeight); //110 110
</script>
</body>
</html>
代碼解析
獲取元素:
var div = document.querySelector('#box');獲取相對寬高:
console.log(div.offsetWidth, div.offsetHeight); //112 112 console.log(div.clientWidth, div.clientHeight); //110 110
offsetWidth和offsetHeight包括了寬度/高度、內(nèi)邊距和邊框。clientWidth和clientHeight僅包括寬度/高度和內(nèi)邊距,不包括邊框。
5. 動畫效果
代碼片段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<input type="button" value="帶你飛">
<div id="box"></div>
<script>
//1. 獲取元素
var div = document.querySelector('#box');
var fly = document.querySelector('input');
//2. 添加事件
fly.onclick = function () {
var speed = 1;
setInterval(function () {
div.style.left = div.offsetLeft + speed++ + 'px';
}, 30);
}
</script>
</body>
</html>
代碼解析
獲取元素:
var div = document.querySelector('#box');
var fly = document.querySelector('input');添加事件:
fly.onclick = function () {
var speed = 1;
setInterval(function () {
div.style.left = div.offsetLeft + speed++ + 'px';
}, 30);
}點(diǎn)擊按鈕后,使用setInterval定時(shí)器每30毫秒更新一次left樣式屬性,使div元素逐漸向右移動。
6. 表格操作與事件處理
代碼片段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table border="1">
<tr>
<td>商品名稱</td>
<td>商品價(jià)格</td>
<td>商品圖片</td>
<td>操作</td>
</tr>
<tr data-good-id="sp1">
<td><input type="hidden" value="1">筆記本</td>
<td>139999</td>
<td>33333</td>
<td><a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="buy">購買</a></td>
</tr>
<tr data-good-id="sp2">
<td><input type="hidden" value="2">手機(jī)</td>
<td>9999</td>
<td>33333</td>
<td><a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="buy">購買</a></td>
</tr>
<tr data-good-id="sp3">
<td><input type="hidden" value="3">平板</td>
<td>1999</td>
<td>33333</td>
<td><a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="buy">購買</a></td>
</tr>
</table>
<script>
//1. this 代表它所在的function被哪個(gè)對象調(diào)用了,this就代表這個(gè)對象。
//2. 如果沒有明確的調(diào)用對象,則代表window
var buy = document.querySelectorAll('.buy');
//添加事件
for (var i = 0, len = buy.length; i < len; i++) {
buy[i].onclick = function () {
//商品id
var id = this.parentNode.parentNode.dataset.goodId;
// alert(id);
//商品序號
var sn = this.parentNode.parentNode.firstElementChild.firstElementChild.value;
// alert(sn);
var name = this.parentNode.parentNode.firstElementChild.lastChild.nodeValue;
alert(name);
}
}
</script>
</body>
</html>
代碼解析
獲取元素:
var buy = document.querySelectorAll('.buy');添加事件:
for (var i = 0, len = buy.length; i < len; i++) {
buy[i].onclick = function () {
//商品id
var id = this.parentNode.parentNode.dataset.goodId;
//商品序號
var sn = this.parentNode.parentNode.firstElementChild.firstElementChild.value;
//商品名稱
var name = this.parentNode.parentNode.firstElementChild.lastChild.nodeValue;
alert(name);
}
}遍歷所有帶有buy類的鏈接,并為每個(gè)鏈接添加點(diǎn)擊事件。點(diǎn)擊時(shí),通過this關(guān)鍵字獲取當(dāng)前點(diǎn)擊的元素,然后逐層向上查找父元素,最終獲取商品ID、序號和名稱。
結(jié)尾
通過上述代碼片段和技術(shù)解析,我們詳細(xì)介紹了如何使用JavaScript進(jìn)行DOM操作、事件處理、屬性操作、內(nèi)容操作、尺寸和位置的獲取,以及實(shí)現(xiàn)簡單的動畫效果。這些技術(shù)點(diǎn)不僅涵蓋了基礎(chǔ)的DOM操作,還包括了一些常見的兼容性處理和高級用法。希望本文能幫助讀者更好地理解和掌握J(rèn)avaScript在Web開發(fā)中的應(yīng)用,為后續(xù)的項(xiàng)目開發(fā)打下堅(jiān)實(shí)的基礎(chǔ)。
到此這篇關(guān)于JavaScript DOM操作與事件處理的文章就介紹到這了,更多相關(guān)js dom操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- JavaScript中DOM操作常用事件總結(jié)
- JavaScript DOMContentLoaded事件案例詳解
- JavaScript WebAPI、DOM、事件和操作元素實(shí)例詳解
- 詳解用js代碼觸發(fā)dom事件的實(shí)現(xiàn)方案
- JS前端知識點(diǎn)總結(jié)之頁面加載事件,數(shù)組操作,DOM節(jié)點(diǎn)操作,循環(huán)和分支
- JS實(shí)現(xiàn)同一DOM元素上onClick事件與onDblClick事件并存的解決方法
- js中DOM事件綁定分析
- JS對象與JSON互轉(zhuǎn)換、New Function()、 forEach()、DOM事件流等js開發(fā)基礎(chǔ)小結(jié)
- js學(xué)習(xí)總結(jié)之dom2級事件基礎(chǔ)知識詳解
- JS實(shí)現(xiàn)動態(tài)添加DOM節(jié)點(diǎn)和事件的方法示例
相關(guān)文章
js 數(shù)組操作之pop,push,unshift,splice,shift
本篇文章主要介紹了js數(shù)組操作之pop,push,unshift,splice,shift。需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01
ES6(ECMAScript 6)新特性之模板字符串用法分析
這篇文章主要介紹了ES6(ECMAScript 6)新特性之模板字符串用法,簡單介紹了ES6模板字符串的概念、功能并結(jié)合實(shí)例形式分析了ES6模板字符串的用法,需要的朋友可以參考下2017-04-04
手寫的一個(gè)兼容各種瀏覽器的javascript getStyle函數(shù)(獲取元素的樣式)
這篇文章主要介紹了手寫的一個(gè)兼容各種瀏覽器的javascript getStyle函數(shù),用來取元素的樣式,需要的朋友可以參考下2014-06-06
JavaScript節(jié)點(diǎn)及列表操作實(shí)例小結(jié)
這篇文章主要介紹了JavaScript節(jié)點(diǎn)及列表操作的方法,以實(shí)例的形式較為詳細(xì)的總結(jié)了javascript針對節(jié)點(diǎn)操作的相關(guān)技巧,并給出了一個(gè)完整的節(jié)點(diǎn)操作方法實(shí)例總結(jié),需要的朋友可以參考下2015-08-08
原生js實(shí)現(xiàn)的貪吃蛇網(wǎng)頁版游戲完整實(shí)例
這篇文章主要介紹了原生js實(shí)現(xiàn)的貪吃蛇網(wǎng)頁版游戲完整實(shí)例,可實(shí)現(xiàn)自主選擇游戲難度進(jìn)行貪吃蛇游戲的功能,涉及javascript鍵盤事件及頁面元素的操作技巧,需要的朋友可以參考下2015-05-05
深入理解JavaScript和TypeScript中的class
class 聲明創(chuàng)建一個(gè)基于原型繼承的具有給定名稱的新類,下面這篇文章主要給大家介紹了關(guān)于JavaScript和TypeScript中class的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2018-04-04
用js實(shí)現(xiàn)before和after偽類的樣式修改的示例代碼
本篇文章主要介紹了用js實(shí)現(xiàn)before和after偽類的樣式修改的示例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09

