<h2 class="title">测试</h2>
<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>
效果

const h2=document.querySelector('.title')// classlist.add()添加类名h2.classList.add('title1');
// clsslist.contains():判断是是否包含console.log(h2.classList.contains('title1'));//显示trueconsole.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'));//显示trueh2.classList.toggle('title');console.log(h2.classList.contains('title'));//显示falseconsole.log(h2.classList.contains('title3'));//显示falseh2.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>

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号