欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript DOM操作與事件處理方法

 更新時間:2025年01月07日 11:00:53   作者:前端青山  
本文通過一系列代碼片段,詳細(xì)介紹了如何使用JavaScript進(jìn)行DOM操作、事件處理、屬性操作、內(nèi)容操作、尺寸和位置獲取,以及實現(xiàn)簡單的動畫效果,涵蓋了基礎(chǔ)和高級技術(shù)點,適合初學(xué)者和進(jìn)階開發(fā)者,感興趣的朋友一起看看吧

前言

本文將通過一系列代碼片段,深入探討如何使用JavaScript進(jìn)行DOM操作、事件處理以及獲取和設(shè)置元素屬性。這些示例涵蓋了從基礎(chǔ)到進(jìn)階的技術(shù)點,幫助讀者更好地理解JavaScript在實際項目中的應(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、removetoggle等。

獲取所有類名

console.log(div.classList, div.classList.length);
console.log(div.classList.item(2));

classList是一個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)屬性,如idtitle。

獲取自定義屬性

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
  • offsetWidthoffsetHeight包括了寬度/高度、內(nèi)邊距和邊框。
  • clientWidthclientHeight僅包括寬度/高度和內(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);
}

點擊按鈕后,使用setInterval定時器每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>商品價格</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">手機</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被哪個對象調(diào)用了,this就代表這個對象。
        //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類的鏈接,并為每個鏈接添加點擊事件。點擊時,通過this關(guān)鍵字獲取當(dāng)前點擊的元素,然后逐層向上查找父元素,最終獲取商品ID、序號和名稱。

結(jié)尾

通過上述代碼片段和技術(shù)解析,我們詳細(xì)介紹了如何使用JavaScript進(jìn)行DOM操作、事件處理、屬性操作、內(nèi)容操作、尺寸和位置的獲取,以及實現(xiàn)簡單的動畫效果。這些技術(shù)點不僅涵蓋了基礎(chǔ)的DOM操作,還包括了一些常見的兼容性處理和高級用法。希望本文能幫助讀者更好地理解和掌握J(rèn)avaScript在Web開發(fā)中的應(yīng)用,為后續(xù)的項目開發(fā)打下堅實的基礎(chǔ)。

到此這篇關(guān)于JavaScript DOM操作與事件處理的文章就介紹到這了,更多相關(guān)js dom操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論