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>到此這篇關(guān)于js添加類名的兩種方法的文章就介紹到這了,更多相關(guān)js添加類名內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
D3.js封裝文本實現(xiàn)自動換行和旋轉(zhuǎn)平移等功能
之前小編和大家分享了SVG中如何配合使用text和tspan來實現(xiàn)換行的功能,所以這篇文章對此功能進行一下封裝,以后就可以直接用了。有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10
阻止mousemove鼠標(biāo)移動或touchmove觸摸移動觸發(fā)click點擊事件
這篇文章主要為大家介紹了阻止mousemove或touchmove與click事件同時觸發(fā)技巧,一個按鈕綁定了多個事件,所以就要想辦法阻止 mouse 鼠標(biāo)事件或 touch 觸摸事件 與 click 事件同時觸發(fā),不然每次拖拽按鈕后都會觸發(fā) click 事件,這顯然是不友好的2023-06-06

