如何在 JavaScript 中修改 CSS 类

介绍

在本教程中,您将学习如何使用 JavaScriptclassList对象为您的 DOM 操作项目修改 CSS 类classList对象允许您调整分配给 HTML 元素的 CSS 类。

先决条件

开始你的项目

创建一个index.html文件,并包含一个style带有 CSS 类标签和一个带有以下内容的段落元素id

索引.html
 <style>
  .colorText {
    color: purple;
  }

  .boldText {
    font-weight: bold;
  }

  .bigText {
    font-size: 35px;
  }
</style>

<p id="myText">
  Hello World! 
</p>

现在让我们使用classList属性修改您的文本并应用您的 CSS 类。

使用.add().contains() classList方法

创建一个index.js文件,获取对段落元素的引用,然后调用该classList.add()方法:

索引.js
 const myText = document.getElementById('myText');

myText.classList.add('colorText');

内置classList.add()方法将类应用于您的 HTML 元素。在这种情况下,段落元素中的文本现在将显示为紫色。

您还可以使用classList.contains()返回布尔值方法检查段落元素中是否存在 CSS 类

索引.js
 const myText = document.getElementById('myText');

console.log(myText.classList.contains('colorText')); // true

由于 CSS 类colorText存在于您的段落元素中,您的调用将返回true.

应用.item().remove() classList方法

在您的index.js文件中,向段落元素添加更多 CSS 类:

索引.js
const myText = document.getElementById('myText');

myText.classList.add('boldText');
myText.classList.add('bigText');
console.log(myText.classList); // ['colorText', 'boldText', 'bigText'];

classList属性将每个附加类存储在一个数组中。如果您使用 console out myText.classList,则会输出一个包含您的 CSS 类的数组。

要检查数组中每个 CSS 类的指定索引,请调用该classList.item()方法:

索引.js
const myText = document.getElementById('myText');

myText.classList.item('boldText'); // 2

要删除 CSS 类,请使用以下classList.remove()方法:

索引.js
 const myText = document.getElementById('myText');

myText.classList.remove('bigText');
console.log(myText.classList); // ['colorText', 'boldText'];

一旦您退出myText.classList,您删除的 CSS 类不会出现在数组中,也不会应用于您的段落元素。

现在您可以添加、检查和删除 CSS 类,让我们探索如何放大其他classList方法。

处理classList .toggle()方法

您可以使用该方法而不是同时调用classList.add()classList.remove()classList.toggle()

为此,请在index.js文件中的按钮上实现事件侦听器

索引.js
 textButton.addEventListener('click', () => {
  myText.classList.toggle('newFont');
});

每次单击时,classList.toggle()如果classList数组中不存在 CSS 类将添加它并返回true. 如果 CSS 类存在,该方法将删除该类并返回false.

索引.js
 const anotherClass = myText.classList.toggle('newSize');

console.log(anotherClass); // true --> class was added

您还可以在classList.toggle()方法中添加一个布尔值作为可选的第二个参数这将添加或删除 CSS 类,具体取决于第二个参数的计算方式:

索引.js
const bool = false; 

let firstToggle = myText.classList.toggle('newSize', bool);
console.log(firstToggle);
// false, 'newFont' already exists and will remove from classList array

let secondToggle = shadesEl.classList.toggle('newColor', !bool);
console.log(secondToggle);
// true, 'newColor' does not exist and will add the class

classList.toggle()方法支持使用较短的代码行添加和删除 CSS 类,无论它们是否存在于您的数组中。

结论

classList属性允许在 JavaScript 中更改 HTML 元素及其 CSS 类的更高性能和功能。

如需更多阅读,请查看文章如何修改 DOM 中的属性、类和样式以及电子书了解 DOM — 文档对象模型

觉得文章有用?

点个广告表达一下你的爱意吧 !😁