js添加类名的两种方法
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添加类名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
javascript中tostring()和valueof()的用法及两者的区别
基本上,所有JS数据类型都拥有valueOf和toString这两个方法,null除外。它们俩解决javascript值运算与显示的问题,本文给大家介绍javascript中tostring()和valueof()的用法及两者的区别,对js tostring valueof相关知识感兴趣的朋友一起学习吧2015-11-11JavaScript setTimeout使用闭包功能实现定时打印数值
这篇文章主要介绍了JavaScript setTimeout使用闭包功能实现定时打印数值 的相关资料,需要的朋友可以参考下2015-12-12微信小程序getLocation 需要在app.json中声明permission字段
这篇文章主要介绍了微信小程序getLocation 需要在app.json中声明permission字段,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-03-03
最新评论