将 "myStyle" 类添加到元素:
const list = element.classList;
list.add("myStyle");
亲自试一试 »
从元素中删除 "myStyle" 类:
const list = element.classList;
list.remove("myStyle");
亲自试一试 »
打开和关闭"myStyle":
const list = element.classList;
list.toggle("myStyle");
亲自试一试 »
下面有更多示例。
这个classList
属性返回元素的 CSS 类名。
这个classList
属性返回一个DOM令牌列表。
element.classList
Type | Description |
Object | A DOMTokenList. A list of the class names of an element. |
这个classList
属性是只读的,但您可以使用下面列出的方法在列表中添加、切换或删除 CSS 类:
Name | Description |
---|---|
add() | Adds one or more tokens to the list |
contains() | Returns true if the list contains a class |
entries() | Returns an Iterator with key/value pairs from the list |
forEach() | Executes a callback function for each token in the list |
item() | Returns the token at a specified index |
keys() | Returns an Iterator with the keys in the list |
length | Returns the number of tokens in the list |
remove() | Removes one or more tokens from the list |
replace() | Replaces a token in the list |
supports() | Returns true if a token is one of an attribute's supported tokens |
toggle() | Toggles between tokens in the list |
value | Returns the token list as a string |
values() | Returns an Iterator with the values in the list |
获取 "myDIV" 元素的类名称:
<div id="myDIV" class="myStyle anotherClass thirdClass">
<p>I am myDIV.</p>
</div>
const list = document.getElementById("myDIV").classList;
亲自试一试 »
如果元素具有 "myStyle" 类,则删除 "anotherClass"。
if (element.classList.contains("mystyle")) {
element.classList.remove("anotherClass");
}
亲自试一试 »
在类之间切换以创建下拉按钮:
document.getElementById("myBtn").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
亲自试一试 »
创建粘性导航栏:
// Get the navbar
const navbar = document.getElementById("navbar");
// Get the offset position of the navbar
const sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position
// Remove it when you leave the scroll position
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
亲自试一试 »
element.classList
所有浏览器都支持:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 10-11 | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!