classList 对象实例演示,使用 blur 进行非空验证
一.classList 对象实例演示
const box = document.querySelector(".box");
//parseInt()字符串转换为数字,window.getComputedStyle()全局方法获取计算样式
let borderWidth = parseInt(window.getComputedStyle(box).borderWidth) + 5;
box.style.borderWidth = borderWidth + "px";
//添加
box.classList.add("backgroundColor");
//判断
console.log(box.classList.contains("backgroundColor"));
//移除
box.classList.remove("backgroundColor");
//替换('旧值','新值')
box.classList.replace("box", "borderChange");
//切换,类名有则移除,没有则添加
box.classList.toggle("colorChange");
box.classList.toggle("borderChange");
二.使用 blur 进行非空验证
function check(element) {
//禁用默认行为
event.preventDefault();
//阻止冒泡
event.stopPropagation();
console.log(element.form);
let email = element.form.email;
let password = element.form.password;
if (email.value.length === 0) {
alert("邮箱为空");
email.focus();
return false;
} else if (password.value.length === 0) {
alert("密码为空");
password.focus();
return false;
} else {
return true;
}
}
//focus获取焦点时触发
document.forms.login.email.onfocus = function () {
email.value.length === 0
? false
: console.log(document.forms.login.email.value);
};
document.forms.login.password.onfocus = function () {
password.value.length === 0
? false
: console.log(document.forms.login.password.value);
};
//blur失去焦点时触发
document.forms.login.email.onblur = function () {
if (this.value.length === 0) {
alert("邮箱不能为空");
return false;
}
};
document.forms.login.password.onblur = function () {
if (this.value.length === 0) {
alert("密码不能为空");
return false;
}
};
//change值发生改变且失去焦点时触发
document.forms.login.password.onchange = function () {
console.log("密码已改变");
};
//input值发生改变时触发
document.forms.login.password.oninput = function () {
console.log(this.value);
};