element.classList.toggle中第二个参数的意义是什么? [英] What's the point of the second argument in element.classList.toggle?

查看:114
本文介绍了element.classList.toggle中第二个参数的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 MDN :

toggle方法具有一个可选的第二个参数,该参数将根据第二个参数的真实性来强制添加或删除类名.例如,要删除一个类(如果不存在),可以调用 element.classList.toggle('classToBeRemoved',false); 并添加一个类(如果不存在)可以调用 element.classList.toggle('classToBeAdded',true);

The toggle method has an optional second argument that will force the class name to be added or removed based on the truthiness of the second argument. For example, to remove a class (if it exists or not) you can call element.classList.toggle('classToBeRemoved', false); and to add a class (if it exists or not) you can call element.classList.toggle('classToBeAdded', true);

据我了解, classList 是一个令牌列表,并且列表与数组不同,不能有重复的项.因此,将项目添加到已经具有该项目的列表中不会执行任何操作,而从不包含该列表的列表中删除项目(显然)也不会执行任何操作,这意味着 classList.toggle(className,true) classList.add(className)相同,并且 classList.toggle(className,false) classList.remove(className).

To my understanding, the classList is a token list, and lists, unlike arrays, can't have duplicate items. So adding an item to a list that already has it doesn't do anything and removing an item from a list that doesn't contain it (obviously) doesn't do anything, meaning that classList.toggle(className, true) is identical to classList.add(className) and classList.toggle(className, false) is identical to classList.remove(className).

我想念什么吗?

P.S.无需警告IE兼容性问题.

P.S. no need to warn about IE compatibility issues.

推荐答案

它将简单地允许您执行以下操作:

It would simply allow you to do something like this:

el.classList.toggle("abc", someBool);

代替此:

if (someBool) {
    el.classList.add("abc");
} else {
    el.classList.remove("abc");
}

这篇关于element.classList.toggle中第二个参数的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆