js添加类名的两种方法
作者:吃葡萄不吐葡萄皮嘻嘻
这篇文章主要介绍了js添加类名的两种方法,一种是通过className来添加、删除类名,另一种是通过classList来添加、删除类名,感兴趣的朋友跟随小编一起看看吧
1.通过className来添加、删除类名
添加类名获取元素.className = "类名1 类名2 ..."多个类名用空格隔开
移除类名获取元素名.className = " "直接等于一个空字符串即可删除类名
2.通过classList来添加、删除类名
添加一个类名获取元素名.classList.add("类名");
添加多个类名用逗号隔开获取元素名.classList..add("类名1","类名2","类名3",...); 每个类名需要用引号引起来
移除一个类名获取元素名.classList.remove("类名");
移除多个类名获取元素名.classList.remove("类名1","类名2","类名3",...); 每个类名需要用引号引起来
举个栗子

<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;;
}
</style><input type="text" value="手机">
<script>
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 = ""
}
}
}
</script>到此这篇关于js添加类名的两种方法的文章就介绍到这了,更多相关js添加类名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
