本文由法国 OpenWeb 爱好者 Anthony Ricaud 撰写。
为什么需要 classList
动态 Web 应用程序通常需要其内部机制的视觉反馈,或者需要根据用户的操作显示不同的视觉元素。
为了轻松更改用户界面,您可以通过 DOM API(document.createElement
、div.removeChild
、elt.style.color
等)添加/删除/编辑元素,但只需更新元素的 class
属性即可更改它们如何通过 CSS 显示和设置样式,这更容易。
让我们举个例子。假设您想显示一个具有两种模式的表单:基本模式和具有额外选项的专家模式。
这可以通过 CSS 规则来完成:每种模式都有自己的类和 CSS 代码集。
#anexpertinput.basic {
display: none;
}
#anexpertinput.expert {
display: inline;
}
要动态更改元素的类,可以使用 element.className
。但是,您可能希望添加、删除或切换单个类。过去有两种方法可以做到这一点,使用库或使用正则表达式编写复杂的代码。现在,使用名为 classList
的新 HTML5 API 还有另一种方法,该 API 在 Firefox 3.6 中实现。
让我们看看它如何简化您的代码并同时提高性能。
classList API
这是一个示例,向您展示 classList API 的外观
// By default, start without a class in the div:
// Set "foo" as the class by adding it to the classList
div.classList.add('foo'); // now
// Check that the classList contains the class "foo"
div.classList.contains('foo'); // returns true
// Remove the class "foo" from the list
div.classList.remove('foo'); // now
// Check if classList contains the class "foo"
div.classList.contains('foo'); // returns false: "foo" is gone
// Check if class contains the class "foo",
// If it does, "foo" is removed, if it doesn't, it's added
div.classList.toggle('foo'); // class set to
div.classList.toggle('foo'); // class set to
演示
让我们回到我们最初关于具有基本模式和专家模式的表单的示例 - 查看 实时演示 以查看其运行情况。
如您在下面的代码中看到的,您可以使用一行 JavaScript 在这两种模式之间切换。
Blablablablabla...
#box.expert > #help,
#box.expert > label[for="postpone"],
#box.expert > label[for="lang"] {
display: none;
}
有关 classList 的更多详细信息,请参阅 Mozilla 文档 和 HTML5 规范。
性能
使用 classList API 不仅更容易,而且功能更强大。查看使用 Firefox 3.6 我们观察到的情况。
互操作性
由于其他浏览器供应商尚未实现 HTML5 classList API,因此您仍然需要回退代码。您可以使用 此示例代码 作为回退。
要了解知名 JavaScript 库中 classList 的当前实现情况,请参阅
关于 Paul Rouget
Paul 是一位 Firefox 开发人员。
16 条评论