classlist使用方法_如何通过使用HTML5的classList API在没有jQuery的情况下操作类
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()方法。 如果className在classList中尚不存在,则会引发错误。
<!-- 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使用方法
相关文章:

键盘码 ascii码
ASCII码表 ASCII值 控制字符 ASCII值 控制字符 ASCII值 控制字符 ASCII值 控制字符 0 NUT 32 (space) 64 96 、 1 SOH 33 ! 65 A 97 a 2 STX 34 ” 66 B 98 b 3 ETX 35 # 67 C 99 c 4 EOT 36 $ 68 D 100 d 5 ENQ 37 % 69 E 101 e 6 ACK 38 & 70 F 102 f 7 BEL …

Swift -布局框架SnapKit使用
SnapKit 1 安装 SnapKit github地址 2 文档地址 在线文档 // // ViewController.swift // SK_SnapKit // // Created by coder on 2019/3/6. // Copyright © 2019 AlexanderYeah. All rights reserved. //import UIKit import SnapKitclass ViewController: UIVie…

Hadoop概念学习系列之为什么hadoop/spark执行作业时,输出路径必须要不存在?(三十九)...
很多人只会,但没深入体会和想为什么要这样? 拿Hadoop来说,当然,spark也一样的道理。 输出路径由Hadoop自己创建,实际的结果文件遵守part-nnnn的约定。 如何指定一个已有目录作为Hadoop作业的输出路径,作业将…

已知环境静态障碍物避障_我女儿如何教我无障碍环境
已知环境静态障碍物避障by Drew通过德鲁 我女儿如何教我无障碍环境 (How my daughter taught me about accessibility) 在过去的几个月里,花了很多时间学习编程知识,这真是令人大开眼界。 面对似乎无穷无尽的技术和概念(即使是最简单的事物),…

IIS 部署 node.js ---- 基础安装部署
一些可能有用的相关文章: https://blogs.msdn.microsoft.com/scott_hanselman/2011/11/28/window-iisnode-js/ http://blog.csdn.net/puncha/article/details/9047311 20161123,这几天看了一些相关文章,觉得说的不太清楚,记录一下…

Qt中的 Size Hints 和 Size Policies
sizeHint 这个属性所保存的 QSize 类型的值是一个被推荐给窗口或其它组件(为了方便下面统称为widget)的尺寸,也就是说一个 widget 该有多大,它的一个参考来源就是这个 sizeHint 属性的值,而这个值由 sizeHint() 函数来…

atom 中首次使用git_使用Atom获得更好的Git提交消息
atom 中首次使用gitby Hasit Mistry通过Hasit Mistry 使用Atom获得更好的Git提交消息 (Get Better Git Commit Messages with Atom) Recently, I came across two enlightening posts about writing better Git commit messages. These posts give suggestions about how a we…

正确理解ThreadLocal
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt107 首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程…

PHP-密码学算法及其应用-对称密码算法
转自:http://www.smatrix.org/bbs/simple/index.php?t5662.html //目录1. PHP的散列函数及其应用2. PHP中的对称密码算法及其应用3. PHP的公钥密码算法及其应用///2 PHP中的对称密码算法及其应用前一段时间一直想写完PHP中的密码学算法及其应用的三大部分…

Swift4 String截取字符串
var str1 "AlexanderYeah";// 1 截取字符串的第一种方式 // prefix 截取前3个字符串 var str2 str1.prefix(3); print(str2);// suffix 截取后3个字符串 var str3 str1.suffix(3); print(str3);// 2 截取一个范围的字符串 // 从0开始 到倒数第二位结束 let idx1 …

angular react_Angular 2 vs React:将会有鲜血
angular reactAngular 2 has reached Beta and appears poised to become the hot new framework of 2016. It’s time for a showdown. Let’s see how it stacks up against 2015’s darling: React.Angular 2已达到Beta版本,并有望成为2016年炙手可热的新框架。该…

Welcome to Swift (苹果官方Swift文档初译与注解三十四)---241~247页(第五章-- 函数)
In-Out Parameters (全局参数) 像前面描述的参数变量,只能在函数体内进行修改,如果你需要函数修改的它的参数值,并且希望这些改变在函数调用结束后仍然有效,可以定义使用全局参数. 定义全局参数使用关键字inout,全局参数的值在函数调用的时候进行传递,在函数体内进行修改,最后函…

递归 尾递归_代码简报:递归,递归,递归
递归 尾递归Here are three stories we published this week that are worth your time:这是我们本周发布的三个值得您关注的故事: A beginner’s guide to recursion: 6 minute read 递归初学者指南: 6分钟阅读 Things you probably didn’t know you …

Hadoop 生态系统
当下 Hadoop 已经成长为一个庞大的生态体系,只要和海量数据相关的领域,都有 Hadoop 的身影。下图是一个 Hadoop 生态系统的图谱,详细列举了在 Hadoop 这个生态系统中出现的各种数据工具。这一切,都起源自 Web 数据爆炸时代的来临。…

socket通信——通过Udp传输方式,将一段文字数据发送出去
需求:通过Udp传输方式,将一段文字数据发送出去定义一个Udp发送端思路:1、建立updsocket服务2、提供数据,并将数据封装到数据包中。3、通过socket服务的发送功能,将数据包发出去4、关闭资源。import java.net.*; class …

编码中统一更该变量的快捷键_流媒体的7种方式使您成为更好的编码器
编码中统一更该变量的快捷键by freeCodeCamp通过freeCodeCamp 流媒体的7种方式使您成为更好的编码器 (7 Ways Streaming Makes you a Better Coder) After coding live on twitch.tv for dozens of hours, I’m convinced that streaming makes you a better coder. Here’s w…

AutoConfig工具使用
下载安装Auto工具包: http://code.taobao.org/mvn/repository/com/alibaba/citrus/tool/antx-autoconfig/1.0.9/antx-autoconfig-1.0.9.tgzhttp://code.taobao.org/mvn/repository/com/alibaba/citrus/tool/antx-autoexpand/1.0.9/antx-autoexpand-1.0.9.tgztar zxv…

Spark2 ML 学习札记
摘要: 1.pipeline 模式 1.1相关概念 1.2代码示例 2.特征提取,转换以及特征选择 2.1特征提取 2.2特征转换 2.3特征选择 3.模型选择与参数选择 3.1 交叉验证 3.2 训练集-测试集 切分 4.spark新增SparkSession与DataSet 内容: 1.pipeline …

xCode 开发快捷键
Ctrl CMD 右箭头返回上一个编辑的界面Ctrl CMD 左箭头返回后一个编辑的界面CMD Option 左箭头区域代码折叠CMD Option 右箭头区域代码展开Shift CMD Option 左箭头折叠界面内所有的代码Shift CMD Option 右箭头展开界面内所有的代码CMD Ctrl 上下箭头.h 和 .m …

javascript模块_JavaScript模块第2部分:模块捆绑
javascript模块by Preethi Kasireddy通过Preethi Kasireddy JavaScript模块第2部分:模块捆绑 (JavaScript Modules Part 2: Module Bundling) In Part I of this post, I talked about what modules are, why developers use them, and the various ways to incorp…

idea上实现github代码同步
1.先将github远程仓库clone到本地 2.将本地仓库中的项目导入到idea中 3.如果你的项目代码不是放在仓库的根目录下,idea会识别到你的项目是在git仓库目录下,必须点击add root才能匹配路径。 4.add root后会发现右击项目时会多了一个git选项 5.在git选项中…

iOS12 UITabbar Item 向上漂移错位的bug
[[UITabBar appearance] setTranslucent:NO]; 加此行代码 完美解决此bug

jQuery学习笔记(一)
补充一些自己容易忘的知识点: event.stopPropagation() 阻止事件冒泡 event.preventDefault() 阻止事件的默认行为 return false 相当于event.stopPropagation() event.preventDefault() 。除了阻止默认行为之外,还会阻止事件冒泡。 转载于:https://www.cnblogs.…

随机网络构建_构建随机报价机
随机网络构建by Ayo Isaiah通过Ayo Isaiah 构建随机报价机 (Building a Random Quote Machine) I really wasn’t entirely satisfied with my first attempt at building a Random Quote Generator on Free Code Camp. It was ugly, and the quotes were too long, so I didn…

20145231 《信息安全系统设计基础》第11周学习总结
20145231《信息安全系统设计基础》第11周学习总结 教材学习内容总结 异常 异常是异常控制流的一种形式,由硬件和操作系统实现。简单来说,就是控制流中的突变。 出现异常的处理方式: 1.处理器检测到有异常发生 2.通过异常表,进行间…

JAR命令使用
jar 命令详解 jar 是随 JDK 安装的,在 JDK 安装目录下的 bin 目录中,Windows 下文件名为 jar.exe,Linux 下文件名为 jar。它的运行需要用到 JDK 安装目录下 lib 目录中的 tools.jar 文件。不过我们除了安装 JDK 什么也不需要做,因…

捍卫者usb管理控制系统_捍卫超模块化JavaScript
捍卫者usb管理控制系统by Mike Groseclose通过Mike Groseclose 捍卫超模块化JavaScript (In Defense of Hyper Modular JavaScript) Last week npmgate was a big topic for the JavaScript community. For those of you who haven’t been following what happened, here’s …
Android开发——布局性能优化的一些技巧(一)
0. 前言上一篇我们分析了为什么LinearLayout会比RelativeLayout性能更高,意义在于分析了这两种布局的实现源码,算是对一个小结论的证明过程,但是对布局性能的优化效果,对这两种布局的选择远不如减少布局层级、避免过分绘制、按需加…

1-RAC基础
1 安装 pod ‘ReactiveObjC’ RAC 其实大大减少了代码量 2 基本使用 // 0 RAC 中最为常见的类 信号类/*RACSignal:信号类1.通过RACSignal 创建1个信号(默认:冷信号)2.通过订阅者,订阅信号信号(变成:热信号…

static用法总结
C的static有两种用法:面向过程程序设计中的static和面向对象程序设计中的static。前者应用于普通变量和函数,不涉及类;后者主要说明static在类中的作用。 一、面向过程设计中的static1、静态全局变量2、静态局部变量3、静态函数二、面向对象的…