element.classList.toggle中第二个参数的意义是什么?

编程入门 行业动态 更新时间:2024-10-27 23:19:09
本文介绍了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中第二个参数的意义是什么?

本文发布于:2023-10-24 02:51:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第二个   意义   参数   element   classList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!