ClassList对象实践
1. 给出一个h2
HTML
<h2 class="title">测试</h2>
添加css样式
<style>
.title {
background-color: green;
color: rgb(244, 246, 248);
}
.title1 {
background-color: rgb(18, 26, 150);
}
.title2{
color:chartreuse;
}
.title3 {
background-color: orange;
color:burlywood;
}
</style>
效果
为h2添加一个叫‘title1’的类名从而改变它的样式后效果
const h2=document.querySelector('.title')
// classlist.add()添加类名
h2.classList.add('title1');
判断h2是否包含其他类名
// clsslist.contains():判断是是否包含
console.log(h2.classList.contains('title1'));//显示true
console.log(h2.classList.contains('title3'));//显示false
删除类名
// classlist.remove()删除类名
h2.classList.remove('title');
console.log(h2.classList.contains('title'));
替换类名
// classlist.replace()替换类名
h2.classList.replace('title1','title');
console.log(h2.classList.contains('title'));
console.log(h2.classList.contains('title1'));
动态添加类名
// classlist.toggle()动态切换css
// 如果之前没有这个样式,就自动添加,如果有,则去掉这个样式
console.log(h2.classList.contains('title'));//显示true
h2.classList.toggle('title');
console.log(h2.classList.contains('title'));//显示false
console.log(h2.classList.contains('title3'));//显示false
h2.classList.toggle('title3');
console.log(h2.classList.contains('title3'));//显示true
失去焦点时进行非空验证
<body>
<form action="" method="post" id="login">
<label class="title">用户登录</label>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" value="" autofocus />
<label for="password">密码:</label>
<input type="password" id="password" name="password" />
<!-- 1. type="button" 这是一个普通按钮,没有提交行为 -->
<button name="submit" onclick="check(this)">登录</button>
</form>
<script>
function check(ele) {
// 禁用默认行为
event.preventDefault();
// 防止冒泡
event.stopPropagation();
// 非空验证
let email = ele.form.email;
let password = ele.form.password;
if (email.value.length === 0) {
alert('邮箱不能为空');
email.blur();
return false;
} else if (password.value.length === 0) {
alert('密码不能为空');
password.blur();
return false;
} else {
alert('验证通过');
}
}
document.forms.login.email.onblur = function() {
if (this.value.length === 0) {
alert('不能为空');
return false;
}
}
</script>
</body>