MENU
通过className来添加或删除类名
通过classList来添加或删除类名
className与classList的区别
效果图
案例
html
<input type="text" value="手机" />
style
input {
outline: none;
height: 35px;
line-height: 35px;
border: 1px solid #ccc;
color: #999;
text-indent: 1rem;
display: inline-block;
transition: all .3s;
}
.active {
border: 1px solid skyblue;
color: #333;
}
.active2 {
box-shadow: 0 0 3px 2px pink;
}
JavaScript
window.onload = function () {
document.querySelector('input').onfocus = function () {
this.value = "";
// 方法一:
// this.style.color = "#333";
// this.style.border = "1px solid skyblue";
// 方法二:
this.classList.add("active", "active2");
// 方法三:
// this.className = "active active2";
}
// trim() 去除空格
document.querySelector('input').onblur = function () {
if (this.value.trim() === "") {
this.value = "手机";
// 方法一:
// this.style.color = "#999";
// this.style.border = "1px solid #ccc";
// 方法二:
this.classList.remove("active", "active2");
// 方法三:
// this.className = "";
}
}
}