记下笔记
- 添加新的类名,如已经存在,取消添加
classList.add( newClassName );
- 确定元素中是否包含指定的类名,返回值为true 、false;
classList.contains( oldClassName );
- 移除已经存在的类名;
classList.remove( oldClassName );
- 如果classList中存在给定的值,删除它,否则,添加它;
classList.toggle( className );
- 类名替换
classList.replace( oldClassName,newClassName );
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.newMystyle{
width: 300px;
height: 50px;
background-color: pink;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<p>点击按钮为 DIV 元素添加 "mystyle" 类。</p>
<button onclick="add()">点我增加class</button>
<button onclick="remove()">点我删除class</button>
<button onclick="myContains()">是否包含</button>
<button onclick="toggle()">切换类</button>
<button onclick="myReplace()">替换类</button>
<p><strong>注意:</strong> Internet Explorer 9 及更早 IE 版本浏览器不支持 classList 属性。</p>
<div id="myDIV"> 我是一个 DIV 元素。</div>
</body>
<script>
const oDiv = document.getElementById('myDIV');
//添加类
function add() {
oDiv.classList.add("mystyle");
//添加多个
// oDiv.classList.add("mystyle", "anotherClass", "thirdClass");
}
//删除类
function remove() {
oDiv.classList.remove("mystyle");
}
//确定是否包含给定的类
function myContains() {
if (oDiv.classList.contains("anotherClass")) {
oDiv.classList.remove("anotherClass");
} else {
alert("找不到此类");
}
// console.log(oDiv.classList.contains("mystyle"));
}
//切换类:存在删除,不存在,就添加;
function toggle() {
oDiv.classList.toggle("mystyle")
}
//替换类:新类newMystyle替换老类mystyle;
function myReplace() {
oDiv.classList.replace("mystyle","newMystyle")
}
//迭代类;
for(var i = 0,len = oDiv.classList.length; i < len; i++){
doSomething(oDiv.classList[i]);
}
</script>
</body>
</html>
ES6 代码块使用
const hasClass = (el, className) => el.classList.contains(className);
// Example
hasClass(document.querySelector("p.mystyle "), "mystyle"); // true
const toggleClass = (el, className) => el.classList.toggle(className);
// Example
toggleClass(document.querySelector( p.mystyle ), mystyle); // 该段不再有 "mystyle" 类
网友评论