本文目錄一覽:
用js怎麼給name為某某的加上類樣式
獲取所有該name的元素
var es = document.getElementsByName(“要找的name”)
這樣會獲取所有是該name的一個數組,如果是一個可以直接用 es[0]得到
不過name有個缺點,就是除了表單元素 ie下是獲取不到的
es[0].className = es[0].className+” 你的class”;//注意class名前加個空格
如果是多個可以循環es這個數組,給每個加上
js 怎麼通過class改變樣式
js通過class改變樣式,可以使用Dom的className屬性設置元素的樣式。完整示例代碼如下:
!DOCTYPE html
html
head
meta charset=”utf-8″
title測試頁面/title
style type=”text/css”
.themeCls {
color: #000;
background-color: #f60;
line-height: 25px;
}
/style
/head
body style=”background-color:#ccc;”
span id=”theme”這是一段測試文本br /用來測試js通過class改變樣式/span
script type=”text/javascript”
var domTheme = document.getElementById(“theme”);
theme.className = “themeCls”;
/script
/body
/html
具體操作步驟如下:
1、新建一個html文件,命名為t.html。
2、打開t.html。
3、在t.html中寫入html結構代碼,其中設置需要添加class類的元素的ID為“theme”。代碼如下:
!DOCTYPE html
html
head
meta charset=”utf-8″
title測試頁面/title
/head
body style=”background-color:#ccc;”
span id=”theme”這是一段測試文本br /用來測試js通過class改變樣式/span
/body
/html
4、設置一個css類,命名為”themeCls”,用於在javascript操作時給元素添加clsss。”themeCls”類為了方便觀察效果,設置css規則為字體顏色為黑色#000,背景為橙色#f60,行高為25像素。代碼如下:
style type=”text/css”
.themeCls {
color: #000;
background-color: #f60;
line-height: 25px;
}
/style
5、編寫javascript代碼,獲取ID為“theme”的元素並設置元素的class類為“themeCls”,代碼如下:
script type=”text/javascript”
var domTheme = document.getElementById(“theme”);
domTheme .className = “themeCls”;
/script
6、打開瀏覽器,瀏覽t.html頁面,發現頁面中”這是一段測試文本用來測試js通過class改變樣式”這一段文本字體顏色呈現黑色,背景呈現橙色,說明我們為元素添加class類“themeCls”成功了。
js通過className可以修改什麼
修改樣式,比如說。
meta http-equiv=”Content-Type” content=”text/html;charset=utf-8″ /
style
.red{
color:red;
}
.blue{
color:blue;
}
/style
body
p class=”red” id=”test”111111/p
p id=”color”/p
/body
script
document.getElementById(“color”).innerHTML = ‘該p標籤的className=’+document.getElementById(“test”).className+’,3秒後變化’;
setTimeout(function() {
document.getElementById(“test”).className = ‘blue’;
document.getElementById(“color”).innerHTML = ‘該p標籤的className=’+document.getElementById(“test”).className;
}, 3000);
/script
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/246861.html