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 polyfill.

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

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 DOMTokenList. 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属性将返回DOMTokenList 它包含应用于元素的所有类以及length属性,该属性表示该元素上的类总数。

Take a look at this example:

看一下这个例子:

<!-- html --><section class="content-wrapper about animated" id="about"></section>
//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()方法即可。 请注意,如果元素中已经存在类名,则不会再次添加它。

<!-- html --><span class="heading" id="headline"></span>
//JavaScriptdocument.getElementById("headline").classList.add("title"); //gives class="heading title"

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

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

<!-- html --><span class="heading" id="headline"></span>
//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中尚不存在,则会引发错误。

<!-- html --><header class="masthead clearfix" id="header"></header>
//JavaScriptdocument.getElementById("header").classList.remove("masthead"); //gives class="clearfix"

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

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

<!-- html --><header class="masthead clearfix headline" id="header"></header>
//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:

例如:

<!-- html --><button class="hidden" id="btn">Click Me</button>
//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:

这是我最终所做的:

<!-- html --><div class="menu" id="menu" onclick="hasClass()"></div>
//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属性:

<!-- html --><nav class="nav hidden" id="navbar"></nav>
//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 Twitter. For more articles like this one, check out my blog. Thanks for reading!

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

翻译自: https://www.freecodecamp.org/news/how-to-manipulate-classes-using-the-classlist-api-f876e2f58236/

classlist使用方法

classlist使用方法_如何通过使用HTML5的classList API在没有jQuery的情况下操作类相关推荐

  1. python在材料模拟中的应用_材料模拟python_模拟-python模拟-在不妨碍实现的情况下修补方法...

    此答案解决了Quuxplusone用户提供的赏金中提到的其他要求: 对于我的用例而言,重要的是它可以与MagicMock一起使用,即,它不需要我在构造Potato(在此示例中为spud)实例与调用sp ...

  2. rtsp协议_如何在RTSP协议视频智能平台EasyNVR未登录的情况下调用通道直播的接口?...

    原标题:如何在RTSP协议视频智能平台EasyNVR未登录的情况下调用通道直播的接口? TSINGSEE青犀视频云边端架构全线都提供了丰富的API接口,用户可以自由调用进行二次开发.在本文之前,我们博 ...

  3. h5的fetch方法_扣丁学堂HTML5分享h5中的fetch方法解读

    扣丁学堂HTML5分享h5中的fetch方法解读 2018-07-06 14:43:10 725浏览 本篇文章扣丁学堂 Fetch概念: fetch身为H5中的一个新对象,他的诞生,是为了取代ajax ...

  4. 安卓获取mysql数据封装方法_数据库:安卓封装的原生api

    1.数据库的管理类 package com.biyu6.creatdb; import android.content.Context; import android.database.sqlite. ...

  5. mysql workbench修改密码_在MySQL Workbench8.0中,忘记MySQL root密码的情况下修改密码...

    适用:如果你已经安装好MySQL,但因为忘记root密码且不想重新下载而无法建立连接,那么本文可能对你有用 前提:已经在环境变量中配置好mysql路径 步骤: Step1.准备配置文件 (1)查看根目 ...

  6. mysql workbench改密码_在MySQL Workbench8.0中,忘记MySQL root密码的情况下修改密码

    适用:如果你已经安装好MySQL,但因为忘记root密码且不想重新下载而无法建立连接,那么本文可能对你有用 前提:已经在环境变量中配置好mysql路径 步骤: Step1.准备配置文件 (1)查看根目 ...

  7. 挣钱的好方法_在“星露谷”赚钱的5种方法

    挣钱的好方法 When you're first starting out in Stardew Valley, it might be challenging to figure out how t ...

  8. 【图论】已知度数列情况下的简单无向图的判断方法

    感谢评论区大佬@goodloveyourlove补充的判断度数列是否能构成无向树的方法与例子. 关于度数列是否能构成无向树的判断方法可以移步至评论区. ======================== ...

  9. html5退出全屏触发的方法_好程序员web前端分享HTML5常见面试题集锦二

    web前端分享HTML5常见面试题集锦第二篇,希望对大家有所帮助. 1. 方法1: html,body{height: 100%;} body{ margin: 0;display: flex; ju ...

最新文章

  1. 机器学习(一)—— 线性回归
  2. java菜鸟到cto 图_从菜鸟到入门,掌握 Log4j
  3. 下班理财超过上班赚钱
  4. perl java远程调用函数调用_如何从Java调用Perl?
  5. 5-去掉a标签下划线,禁止a标签的跳转
  6. php_redis配置安装php_redis-5.1.1-7.4-nts-vc15-x64.zip
  7. md文件 markdown打开工具(typora)
  8. 基于单片机的功放protues_音响放大器proteus仿真
  9. 适合外贸建站的vatage主题教程
  10. 上海招聘 | 上海人工智能实验室:自动驾驶感知算法研究员、实习生等
  11. 中标麒麟Neokylin7桌面版安装指南——基于VirtualBox虚拟机
  12. 咸鱼Maya笔记—摄影表
  13. MDK5+CubeMX仿真STM32F03一站式解决
  14. 算法高级(40)-基于分治算法完美解决的人类基因组计划
  15. 数据分析学习之roc曲线
  16. 怎么撰写一份优秀的数据分析报告(五)
  17. Android 9 P静默安装/卸载App适配终极指南
  18. Struts1、Struts2及SpringMVC对比
  19. npm run build报错Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of
  20. 用原生js+html写一个像素鸟游戏

热门文章

  1. select三级联动 怎么删除前一个的_python测试开发django57.xadmin选项二级联动
  2. 云开发使用 got 的 get/post 传参请求示例代码
  3. devServer proxy跨域 设置代理 proxy
  4. php批量修改文件名
  5. json转换模型利器--JSONExport
  6. 3D Touch介绍: 一个数字压力器App和Quick Actions
  7. 5分钟 搭建免费个人博客
  8. vue组件定义、组件的切换、组件的通信、渲染组件的几种方式(标签、路由、render)...
  9. [转]C++11 随机数学习
  10. 一次被僵尸网络病毒攻击的过程