classlist

tech2023-08-09  112

classlist

Since the creation of HTML and the birth of the first websites, developers and designers have tried to customize the look and feel of their pages. This need became so important that a standard, called CSS, was created to properly manage style and separate it from the content. In today’s highly interactive websites, you often need to add, remove, or toggle class names (usually referred to as “CSS classes”). Historically, dealing with these changes in JavaScript was slightly complicated because there were no built-in methods to perform these actions. This was the case until HTML5 introduced the classList API. In this article, we’ll discover how this API works and the methods it provides.

自从HTML的创建和第一个网站的诞生以来,开发人员和设计师就尝试自定义其页面的外观。 这种需求变得如此重要,以至于创建了一个称为CSS的标准来正确管理样式并将其与内容分离。 在当今高度互动的网站中,您通常需要添加,删除或切换类名(通常称为“ CSS类”)。 从历史上看,处理JavaScript中的这些更改有些复杂,因为没有内置方法可以执行这些操作。 在HTML5引入classList API之前就是这种情况。 在本文中,我们将发现此API的工作方式及其提供的方法。

Note: The term “CSS classes” is often used to refer to class names. These are the strings you put inside the class attribute of an element. However, there is an interesting article suggesting that the term is incorrect and you should avoid it. For the sake of brevity, in this article I’m going to use the term “classes” as a shortcut for “class names”.

注意:术语“ CSS类”通常用于指代类名。 这些是您放入元素的class属性中的字符串。 但是,有一篇有趣的文章建议该术语不正确,您应该避免使用它。 为了简洁起见,在本文中,我将使用术语“类”作为“类名”的快捷方式。

什么是classList API? (What is the classList API?)

The classList API provides methods and properties to manage class names of DOM elements. Using it, we can perform operations such as adding and removing classes, or checking if a given class is present on an element. The classList API exposes these methods and properties via an attribute of the DOM element, called classList. This attribute is of type DOMTokenList, and contains the following methods and properties:

classList API提供了管理DOM元素的类名称的方法和属性。 使用它,我们可以执行操作,例如添加和删除类,或检查元素上是否存在给定的类。 班级列表API通过DOM元件,称为的属性公开这些方法和属性classList 。 此属性的类型为DOMTokenList ,并且包含以下方法和属性:

add(class1, class2, ...): Adds one or more classes to the element’s class list.

add(class1, class2, ...) :将一个或多个类添加到元素的类列表中。

contains(class): Returns true if the list of classes contains the given parameter, and false otherwise.

contains(class) :如果类列表包含给定参数,则返回true否则返回false 。

item(index): Returns the class at position index, or null if the number is greater than or equal to the length of the list. The index is zero-based, meaning that the first class name has index 0.

item(index) :返回位置index处的类;如果数字大于或等于列表的长度,则返回null 。 索引从零开始,这意味着第一类名称的索引为0。

length: This is a read-only property that returns the number of classes in the list.

length :这是一个只读属性,它返回列表中的类数。

remove(class1, class2, ...): Removes one or more classes from the element’s class list.

remove(class1, class2, ...) :从元素的类列表中删除一个或多个类。

toString(): Returns the element’s list of classes as a string.

toString() :以字符串形式返回元素的类列表。

toggle(class[, force]): Removes the given class from the class list, and returns false. If the class didn’t exist, it is added, and the function returns true. If the second argument is provided, it’ll force the class to be added or removed based on its truthiness. For example, setting this value to true causes the class to be added, regardless of whether or not it already existed. By setting this value to false, the class will be removed.

toggle(class[, force]) :从类列表中删除给定的类,并返回false 。 如果该类不存在,则添加该类,然后该函数返回true 。 如果提供了第二个参数,它将根据其真实性强制添加或删除该类。 例如,将此值设置为true会导致添加类,而不管其是否已经存在。 通过将此值设置为false ,将删除该类。

If you’re familiar with jQuery, you may think that the add() and remove() methods perform the same operation on multiple classes by passing a list of space-separated class names (for example add("red bold bigger")). This is not the case. To add or remove more classes at once, you’ve to pass a string for each classes (for example add("red", "bold", "bigger")). As I pointed out, the toggle() method has an optional argument that we can use to force a given action. In other words, if the second parameter of toggle() is false, it acts as the remove() method; if the second parameter is true, it acts as the add() method.

如果您熟悉jQuery,则可能会认为add()和remove()方法通过传递以空格分隔的类名列表(例如add("red bold bigger") )对多个类执行相同的操作。 。 不是这种情况。 要一次添加或删除更多类,您必须为每个类传递一个字符串(例如add("red", "bold", "bigger") )。 正如我指出的那样, toggle()方法具有一个可选参数,我们可以使用该参数来强制执行给定的操作。 换句话说,如果toggle()的第二个参数为false ,则它用作remove()方法; 如果第二个参数为true ,则它用作add()方法。

Now that we’ve described the methods and the properties of this API, let’s see some examples of it in action. Each of the code samples shown below will perform an action assuming the presence of the following HTML element on the page.

现在,我们已经描述了该API的方法和属性,下面让我们来看一下它的一些示例。 假定页面上存在以下HTML元素,下面显示的每个代码示例都将执行一个操作。

<span id="element" class="description"></span>

新增课程 (Adding a Class)

To add the class name “red” to the class attribute of the element, we can write the following:

要将类名称“ red”添加到元素的class属性,我们可以编写以下内容:

document.getElementById('element').classList.add('red'); // class="description red"

To add multiple classes, for example “red” and “bold”, we can write this:

要添加多个类,例如“ red”和“ bold”,我们可以这样编写:

document.getElementById('element').classList.add('red', 'bold'); // class="description red bold"

Note that if one of the provided classes was already present, it won’t be added again.

请注意,如果提供的类之一已经存在,则不会再次添加。

删除课程 (Removing a Class)

To delete a class, for example “description”, we would write the following:

要删除一个类,例如“描述”,我们将编写以下内容:

document.getElementById('element').classList.remove('description'); // class=""

To remove multiple classes at once, we write:

要一次删除多个类,我们编写:

document.getElementById('element').classList.remove('description', 'red'); // class=""

Note that an error is not thrown if one of the named classes provided wasn’t present.

请注意,如果不存在提供的命名类之一,则不会引发错误。

切换课程 (Toggling a Class)

Sometimes we need to add or remove a class name based on a user interaction or the state of the site. This is accomplished using the toggle() method, as demonstrated below.

有时我们需要根据用户交互或站点状态添加或删除类名称。 这是使用toggle()方法完成的,如下所示。

document.getElementById('element').classList.toggle('description'); // class="" document.getElementById('element').classList.toggle('description'); // class="description"

检索课程 (Retrieving a Class)

The classList API provides a method of retrieving class names based on it’s position in the list of classes. Let’s say that we want to retrieve the first and the third classes of our element. We would write the following:

classList API提供了一种根据类名在类列表中的位置来检索类名的方法。 假设我们要检索元素的第一和第三类。 我们将编写以下内容:

document.getElementById('element').classList.item(0); // returns "description" document.getElementById('element').classList.item(2); // returns null

检索班数 (Retrieving the Number of Classes)

Although not very common, there are cases where we may need to know the number of classes applied to a given element. The classList API allows us to retrieve this number through the length property as shown below:

尽管不是很常见,但在某些情况下,我们可能需要知道应用于给定元素的类的数量。 classList API允许我们通过length属性检索此数字,如下所示:

console.log(document.getElementById('element').classList.length); // prints 1

确定是否存在类 (Determine if a Class Exists)

Sometimes we may want to execute a given action based on the presence of a certain class. To perform the test we use the contains() method in the following fashion:

有时我们可能想根据某个类的存在执行给定的动作。 为了执行测试,我们以以下方式使用contains()方法:

if (document.getElementById('element').classList.contains('description')) { // do something... } else { // do something different... }

以字符串形式返回类列表 (Returning the Class List as a String)

To return the list of classes as a string, we can use the toString() method, which is shown below.

要以字符串形式返回类列表,我们可以使用toString()方法,如下所示。

console.log(document.getElementById('element').classList.toString()); // prints "description" document.getElementById('element').classList.add('red', 'bold'); console.log(document.getElementById('element').classList.toString()); // prints "description red bold"

浏览器兼容性 (Browser Compatibility)

The classList API is widely supported among desktop and mobile browsers except for Internet Explorer. IE began supporting this API starting in version 10. More specifically, you can use this API in Chrome 8+, Firefox 3.6+, Internet Explorer 10+, Safari 5.1+, and Opera 11.5+. As we’ve seen the classList API is very straightforward and, as you may guess, polyfilling it is not difficult. Creating your own polyfill should be straightfoward, but if you want something that already exists, you can use classList.js by Eli Grey.

除Internet Explorer外,台式机和移动浏览器都广泛支持classList API。 IE从版本10开始就开始支持此API。更具体地说,您可以在Chrome 8 +,Firefox 3.6 +,Internet Explorer 10 +,Safari 5.1+和Opera 11.5+中使用此API。 正如我们已经看到的,classList API非常简单,并且您可能猜到,对其进行填充并不困难。 创建自己的polyfill应该很简单,但是如果您希望已有的东西可以使用Eli Grey的classList.js 。

演示版 (Demo)

This section provides a simple demo that allows you to experiment with the concepts explained in this article. The demo page contains two basic fields: a select element containing the methods and properties exposed by the API, and a textbox where we can write parameters to pass. As you’ll see, the demo doesn’t explicitly call the methods, but instead uses a simple trick (the use of the JavaScript apply() method), resulting in fewer lines of code. Because some browsers don’t support the API, we perform a check, and if it fails we display the message “API not supported”. If the browser does support the classList API, we attach a listener for the click event of the button so that once clicked, we execute the chosen method.

本部分提供了一个简单的演示,使您可以尝试本文中介绍的概念。 演示页面包含两个基本字段:一个select元素,包含API公开的方法和属性,以及一个文本框,我们可以在其中编写要传递的参数。 如您所见,该演示程序并未显式调用这些方法,而是使用了一个简单的技巧(使用JavaScript apply()方法),从而减少了代码行。 由于某些浏览器不支持API,我们将执行检查,如果失败,则会显示消息“不支持API”。 如果浏览器确实支持classList API,我们将为按钮的click事件附加一个侦听器,以便在click执行选定的方法。

A live demo of the code is available here.

此处提供了代码的实时演示。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>ClassList API Demo</title> <style> body { max-width: 500px; margin: 2em auto; font-size: 20px; } h1 { text-align: center; } .hidden { display: none; } .field-wrapper { margin-top: 1em; } #log { height: 200px; width: 100%; overflow-y: scroll; border: 1px solid #333333; line-height: 1.3em; } .button-demo { padding: 0.5em; margin: 1em; } .author { display: block; margin-top: 1em; } </style> </head> <body> <h1>ClassList API</h1> <h3>Live sample element</h3> <div id="showcase"> &lt;span id="play-element" class="description"&gt;&lt;/span&gt; </div> <h3>Play area</h3> <div> <div class="field-wrapper"> <label for="method">Methods and Properties:</label> <select id="method"> <option value="add">add()</option> <option value="contains">contains()</option> <option value="item">item()</option> <option value="length">length</option> <option value="remove">remove()</option> <option value="toString">toString()</option> <option value="toggle">toggle()</option> </select> </div> <div class="field-wrapper"> <label for="parameter">Parameters (use spaces for multiple parameters):</label> <input type="text" id="parameter"></input> </div> <button id="execute" class="button-demo">Execute</button> </div> <span id="d-unsupported" class="hidden">API not supported</span> <h3>Log</h3> <div id="log"></div> <button id="clear-log" class="button-demo">Clear log</button> <span id="play-element" class="description"></span> <script> if (!'classList' in document.createElement('span')) { document.getElementById('c-unsupported').classList.remove('hidden'); document.getElementById('execute').setAttribute('disabled', 'disabled'); } else { var playElement = document.getElementById('play-element'); var method = document.getElementById('method'); var parameter = document.getElementById('parameter'); var log = document.getElementById('log'); var showcase = document.getElementById('showcase'); document.getElementById('clear-log').addEventListener('click', function() { log.innerHTML = ''; }); document.getElementById('execute').addEventListener('click', function() { var message = method.value; if (method.value === 'length') { message += ': ' + playElement.classList[method.value] } else { var result = playElement.classList[method.value].apply(playElement.classList, parameter.value.split(' ')); showcase.textContent = playElement.outerHTML; if (method.value === 'add' || method.value === 'remove' || method.value === 'toggle') { message += ' class "' + parameter.value + '"'; } else { message += ': ' + result; } } log.innerHTML = message + '<br />' + log.innerHTML; }); } </script> </body> </html>

结论 (Conclusions)

In this article, we’ve learned about the classList API, its methods, and its properties. As we’ve seen, this API helps us in managing the classes assigned to a given element – and it is very easy to use and. This API is widely supported among desktop and mobile browsers, so we can use it safely (with the help of a polyfill if needed). As a last note, don’t forget to play with the demo to gain a better grasp of this API and its capabilities.

在本文中,我们了解了classList API,其方法及其属性。 如我们所见,该API帮助我们管理分配给给定元素的类-而且非常易于使用和。 该API在台式机和移动浏览器中得到广泛支持,因此我们可以安全地使用它(必要时在polyfill的帮助下)。 最后,不要忘了演示一下,以更好地了解此API及其功能。

翻译自: https://www.sitepoint.com/exploring-classlist-api/

classlist

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)