迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 向元素添加类

作者:迹忆客 最近更新:2024/03/13 浏览次数:

本教程将讨论使用 JavaScript 中的 classList 属性向给定元素添加类。


使用 JavaScript 中的 classList 属性向给定元素添加类

如果要向 JavaScript 中的给定元素添加类,可以使用 classList 属性。首先,你必须获取给定的元素,最简单的方法是使用其 id 来获取它。假设没有给元素一个 id;在这种情况下,你可以给它一个唯一的 id 并使用 JavaScript 中的 getElementById 属性获取元素并将其存储在一个变量中。之后,你可以使用该变量通过 classList 属性更改其属性。例如,让我们使用按钮更改文本的类。请参考下面的代码。

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<style type="text/css">
    .newclass {
          width: 90%;
          padding: 30px;
          background-color: red;
          color: yellow;
          font-size: 30px;
}
</style>
<body>
    <button onclick="myFun()">Try it</button>
    <div id="test">
        Adding Class Test
    </div>
    <script type="text/javascript">
        function myFun() {
          var ob = document.getElementById("test");
          ob.classList.add("newclass");
}
    </script>
</body>
</html>

在上面的代码中,我们有一个样式标签,我们在其中设置类对象的属性;在 body 标签内,我们有一个按钮和一些文本,在 script 标签内,我们正在使用其 id 更改文本的类。在此示例中,样式表和 JavaScript 代码放在同一个 HTML 文件中,但你也可以将它们放在单独的文件中并将它们链接到 HTML 文件。要运行上述代码,你需要将代码复制到一个 HTML 文件中并使用浏览器打开它。

正如你在输出中看到的,有一个按钮和一些文本。当你按下此按钮时,文本的类别将被更改。

正如你在输出中看到的那样,由于类的变化,文本形状发生了变化。在此示例中,我们使用按钮来更改元素的类,但你可以更改要更改给定元素类的条件。你不能在 Internet Explorer 9 中使用 classList 属性。相反,你可以使用 += 运算符将该属性添加到给定元素。你必须使用以下行更改脚本标记内 myFun 函数的最后一行。

ob.className += " newclass";

你必须在类名前使用空格,因为可能还有其他类存在。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便