博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
classlist使用方法_如何通过使用HTML5的classList API在没有jQuery的情况下操作类
阅读量:2529 次
发布时间:2019-05-11

本文共 6579 字,大约阅读时间需要 21 分钟。

classlist使用方法

by Ayo Isaiah

通过Ayo Isaiah

如何通过使用HTML5的classList API在没有jQuery的情况下操作类 (How to manipulate classes without jQuery by using HTML5's classList API)

As a front end developer, you often need to change CSS rules based on how a user interacts with elements on a page.

作为前端开发人员,您经常需要根据用户与页面元素的交互方式来更改CSS规则。

In the past, I relied on jQuery to handle these kinds of DOM manipulations for me. But in some cases, it doesn’t make sense to import the whole jQuery library, just so you can perform some basic DOM manipulation.

过去,我依靠jQuery为我处理这类DOM操作。 但是在某些情况下,导入整个jQuery库没有任何意义,只是为了执行一些基本的DOM操作即可。

Luckily, HTML5 offers a way to do this natively, without the need for jQuery.

幸运的是,HTML5提供了一种本地执行此操作的方法,而无需使用jQuery。

我如何发现HTML5的classList方法 (How I discovered HTML5’s classList method)

A few days ago, I was reading some code. I noticed that one project included jQuery as a dependency, just so they could add and remove classes when the user clicked a button on the page. The entire interaction code was only 11 lines of code.

几天前,我在阅读一些代码。 我注意到一个项目将jQuery作为依赖项,以便用户单击页面上的按钮时可以添加和删除类。 整个交互代码只有11行代码。

I thought it was weird they were doing it this way. It was the equivalent of using a bazooka (jQuery) to kill a mosquito (adding and removing classes upon a click).

我以为他们这样做是很奇怪的。 这等效于使用火箭筒(jQuery)杀死蚊子(单击即可添加和删除类)。

It occurred to me that I’d probably done similar things in my previous coding projects. So I decided to try to replicate the same functionality using plain JavaScript and see what I can learn from that.

我想到在以前的编码项目中我可能做过类似的事情。 因此,我决定尝试使用纯JavaScript复制相同的功能,并从中学到什么。

A quick search turned up several options for doing this in plain JavaScript. I went with the classList method because it’s easy to understand and cross-browser support is quite good.

快速搜索提供了几种在纯JavaScript中执行此操作的选项。 我使用classList方法是因为它易于理解,并且跨浏览器的支持非常好。

Note that if you need to support Internet Explorer versions older than IE 11, you may need to find an alternative method or use a .

请注意,如果需要支持早于IE 11的Internet Explorer版本,则可能需要找到其他方法或使用 。

If you’re wholly reliant on using jQuery for DOM handling, this is a great place to start gaining some independence from jQuery.

如果您完全依赖使用jQuery进行DOM处理,那么这是一个开始摆脱jQuery独立性的好地方。

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

The HTML5 classList API provides a way to grab all the classes associated with an element so that you can use JavaScript to modify them.

HTML5 classList API提供了一种获取与元素关联的所有类的方法,以便您可以使用JavaScript对其进行修改。

Using the classList DOM property on an element will return a . This contains all the classes applied to an element, and the length property, which signifies the total number of classes on that element.

在元素上使用classList DOM属性将返回 它包含应用于元素的所有类以及length属性,该属性表示该元素上的类总数。

Take a look at this example:

看一下这个例子:

//JavaScriptvar about = document.getElementById("about"); console.log(about.classList); //logs { 0: "content-wrapper" 1: "about" 2: "animated" length: 3 value: "content-wrapper about animated" }

You can try the above in your browser to see it in action.

您可以在浏览器中尝试上述操作,以查看实际效果。

Getting the classes of an element is all well and good, but it isn’t all that useful on its own. We need a way to manage and update those classes. The classList property provides a few methods that do just that:

获得一个元素的类是一件好事,但它本身并不是那么有用。 我们需要一种管理和更新这些类的方法。 classList属性提供了一些可以做到这一点的方法:

  • add(): Adds specified classes

    add() :添加指定的类

  • remove(): Removes specified classes

    remove() :删除指定的类

  • contains(): Checks whether the specified class exists on the element

    contains() :检查元素上是否存在指定的类

  • toggle(): toggles specified class

    toggle() :切换指定的类

  • index(): returns the class at a specified position in the list

    index() :返回列表中指定位置的类

  • length: returns the number of classes

    length :返回类数

Let’s take a look at each one in turn.

让我们依次看看每个。

新增课程 (Adding classes)

Adding a class to an element is straightforward. Just apply the class name as an argument to the add() method. Note that if the class name already exists on the element, it won’t be added again.

向元素添加类很简单。 只需将类名作为参数应用到add()方法即可。 请注意,如果元素中已经存在类名,则不会再次添加它。

//JavaScriptdocument.getElementById("headline").classList.add("title"); //gives class="heading title"

To add multiple classes, separate each class with a comma:

要添加多个类,请用逗号分隔每个类:

//JavaScriptdocument.getElementById("headline").classList.add("title", "headline"); //gives class="heading title headline"

删除课程 (Removing classes)

To remove a class, all you need to do is pass the class name as an argument to the remove() method. If the class name doesn’t already exist in the classList, an error is thrown.

要删除一个类,您要做的就是将类名作为参数传递给remove()方法。 如果classNameclassList中尚不存在,则会引发错误。

//JavaScriptdocument.getElementById("header").classList.remove("masthead"); //gives class="clearfix"

To remove multiple classes, separate each class with a comma:

要删除多个类,请用逗号分隔每个类:

//JavaScriptdocument.getElementById("header").classList.remove("masthead", "headline"); //gives class="clearfix"

检查是否存在一个类 (Check whether a class exists)

Using the contains() method, we can check whether a specified class is present in an element’s classList and perform operations based on the return value.

使用contains()方法,我们可以检查元素的classList中是否存在指定的类,并根据返回值执行操作。

For example:

例如:

//JavaScriptvar button = document.getElementById("btn"); if (button.classList.contains("hidden")) {   //do something } else {   //do something else}

切换类 (Toggling Classes)

Adding or removing a class based on user action is a common thing to do. This was exactly what I wanted to achieve with classList.

基于用户操作添加或删除类是常见的事情。 这正是我想要通过classList实现的目标。

You can toggle between adding and removing using the toggle() method.

您可以使用toggle()方法在添加和删除之间进行切换

Here’s what I eventually did:

这是我最终所做的:

//JavaScriptvar page = document.getElementById("page"); var menu = document.getElementById("menu"); var nav = document.getElementById("navigation");
function hasClass() {   page.classList.toggle("open");   menu.classList.toggle("active");  nav.classList.toggle("hidden"); }

检查班数 (Check the number of classes)

To find out how many classes are applied to an element, use the length property:

要了解将多少类应用于一个元素,请使用length属性:

//JavaScriptdocument.getElementById("navbar").classList.length; // 2

结语 (Wrapping up)

As you can see, the classList API is easy to use. I encourage you to begin exploring its capabilities in your own applications.

如您所见,classList API易于使用。 我鼓励您开始在自己的应用程序中探索其功能。

Also, leave a comment if you have any questions, or reach out to me on . For more articles like this one, check out . Thanks for reading!

另外,如果您有任何疑问,请发表评论,或在与我联系。 有关此类的更多文章,请查看 。 谢谢阅读!

翻译自:

classlist使用方法

转载地址:http://bdyzd.baihongyu.com/

你可能感兴趣的文章
react高阶组件
查看>>
Android 高手进阶,自己定义圆形进度条
查看>>
Objective-C路成魔【2-Objective-C 规划】
查看>>
Java之旅(三)--- JSTL和EL表情
查看>>
正则匹配
查看>>
单利模式
查看>>
病毒表-相信对大家都有帮助-病毒词典
查看>>
ios 8 联系人ABPeoplePickerNavigationController
查看>>
列表、字典、append
查看>>
关于JAVA IO流的学习
查看>>
C#使用Json.Net遍历Json
查看>>
软工个人项目之词频统计
查看>>
Alpha 冲刺 (7/10)
查看>>
Bmob基础
查看>>
HashMap和HashTable,HashMap中key和value的原理 - 跳刀的兔子 - 博客园
查看>>
Linux自定义分隔符IFS引发的文本处理问题
查看>>
小米商城-题头4
查看>>
permu 莫队 总结
查看>>
Android中Handler原理
查看>>
x/nfu-用gdb查看内存
查看>>