JavaScript DOM操作与事件处理方法

2025-01-08 03:50

本文主要是介绍JavaScript DOM操作与事件处理方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《JavaScriptDOM操作与事件处理方法》本文通过一系列代码片段,详细介绍了如何使用JavaScript进行DOM操作、事件处理、属性操作、内容操作、尺寸和位置获取,以及实现简单的动画效果,涵...

前言

本文将通过一系列代码片段,深入探讨如何使用JavaScript进行DOM操作、事件处理以及获取和设置元素属性。这些示例涵盖了从基础到进阶的技术点,帮助读者更好地理解javascript在实际项目中的应用

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);
        //通过下标获取指定的类名
        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>

JavaScript DOM操作与事件处理方法

代码解析

获取元素

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属性可以直接设置或获取元素的类名。classList提供了一组便捷的方法来操作类名,如addremovetoggle等。

获取所有类名

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

classList是一个DOMTokenList对象,可以通过length属性获取类名数量,通过item方法获取指定索引的类名。

添加事件

onoff.onclick = function () {
    div.classList.toggle('active');
}

toggle方法用于切换类名的存在状态。如果类名存在则移除,不存在则添加。

删除指定类名

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="JavaScript DOM操作与事件处理方法" 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. 设置自定义属性
        div.setAttribute('data-cartId', '999');
   China编程     //5. 删除自定义属性
        div.removeAttribute('data-id');
        console.log(div.dataset.cartId);
        div.id = '';
    </script>
</body>
</html>

JavaScript DOM操作与事件处理方法

代码解析

获取元素

var div = document.getElementById('box');

获取属性

console.log(div.id, div['title']);

可以直接通过属性名访问标准属性,如idtitle

获取自定义属性

console.log(div.getAttribute('data-id'));

使用getAttribute方法获取自定义属性值。

设置自定义属性

div.setAttribute('data-cartId', '999');

使用setAttribute方法设置自定义属性值。

删除自定义属性

div.removeAttribute('data-id');

使用dataset访问自定义属性:

console.log(div.dataset.cartId);

dataset属性提供了一种更方便的方式访问带有data-前缀的自定义属性。

修改id属性:

div.id = '';

3. 内容操作

代码片段

<!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. 添加内容
        txt.value = '姓名:';
        div.innerHTML = '呵呵<i>嘿嘿</i>嘻嘻';
        //2. 获取元素中的内容
        console.log(txt.value);
        console.log(div.innerHTML);
        console.log(div.innerText);
    </script>
</body>
</html>

JavaScript DOM操作与事件处理方法

代码解析

获取元素

var txt = document.querySelector('input');
var div = document.querySelector('#box');

添加内容

txt.value = '姓名:';
div.innerHTML = '呵呵<i>嘿嘿</i>嘻嘻';

value属性用于设置或获取表单元素的值。innerHTML属性用于设置或获取HTML内容,支持HTML标签解析。

获取元素中的内容

console.log(txt.value);
console.log(div.innerHTML);
console.log(div.innerText);

innerText属性仅获取文本内容,不包含HTML标签。

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&gFiJTTrJSPt;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>

JavaScript DOM操作与事件处理方法

代码解析

获取元素

var div = document.querySelector('#box');

获取相对宽高

console.log(div.offsetWidth, div.offsetHeight); //112 112
console.log(div.clientWidth, div.clientHeight); //110 110
  • offsetWidthoffsetHeight包括了宽度/高度、内边距和边框。
  • clientWidthclientHeight仅包括宽度/高度和内边距,不包括边框。

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>

JavaScript DOM操作与事件处理方法

代码解析

获取元素

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>
    <taChina编程ble 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="sp2FiJTTrjsp">
            <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>javascript;</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被哪个对象调用了,this就代表这个对象。
        //2. 如果没有明确的调用对象,则代表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>

JavaScript DOM操作与事件处理方法

代码解析

获取元素

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关键字获取当前点击的元素,然后逐层向上查找父元素,最终获取商品ID、序号和名称。

结尾

通过上述代码片段和技术解析,我们详细介绍了如何使用JavaScript进行DOM操作、事件处理、属性操作、内容操作、尺寸和位置的获取,以及实现简单的动画效果。这些技术点不仅涵盖了基础的DOM操作,还包括了一些常见的兼容性处理和高级用法。希望本文能帮助读者更好地理解和掌握JavaScript在Web开发中的应用,为后续的项目开发打下坚实的基础。

到此这篇关于JavaScript DOM操作与事件处理的文章就介绍到这了,更多相关js dom操作内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于JavaScript DOM操作与事件处理方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1152972

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

判断PyTorch是GPU版还是CPU版的方法小结

《判断PyTorch是GPU版还是CPU版的方法小结》PyTorch作为当前最流行的深度学习框架之一,支持在CPU和GPU(NVIDIACUDA)上运行,所以对于深度学习开发者来说,正确识别PyTor... 目录前言为什么需要区分GPU和CPU版本?性能差异硬件要求如何检查PyTorch版本?方法1:使用命

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义