鏈接:https://www.cnblogs.com/aademeng/articles/6279060.html
在很多情況下,都需要對網頁上元素的樣式進行動態的修改。在JavaScript中提供幾種方式動態的修改樣式,下面將介紹方法的使用、效果、以及缺陷。
1、使用obj.className來修改樣式表的類名。
2、使用obj.style.cssTest來修改嵌入式的css。
3、使用obj.className來修改樣式表的類名。
4、使用更改外聯的css文件,從而改變元素的css
下面是一段html代碼和css代碼用來解釋上面方法的區別的。
CSS
1
2
3
4
5
6
7
|
.style
1
{
margin
:
10px
auto
;
background-color
:
#9999FF
;
display
:
block
;
color
:White;
border
:
1px
solid
white
;
padding
:
10px
25px
;
font-size
:
18px
; }
.style
1:
hover{
background-color
:
#66B3FF
;
cursor
:
pointer
;}
.style
2
{
margin
:
10px
auto
;
background-color
:
gray
;
display
:
block
;
color
:
black
;
border
:
1px
solid
white
;
padding
:
10px
25px
;
font-size
:
18px
; }
.style
2:
hover{
background-color
:
black
;
color
:White;
cursor
:
pointer
}
|
HTML
1
2
3
4
5
6
7
8
9
|
<
div
>
<
input
id
=
"btnB"
type
=
"button"
name
=
"btnLogin"
value
=
"登錄"
class
=
"style1"
/>
<
div
id
=
"tool"
>
<
input
type
=
"button"
value
=
"【obj.style.className】更改樣式"
onclick
=
"changeBackgroundColor()"
/>
<
input
type
=
"button"
value
=
"【obj.style.cssText】更改樣式"
onclick
=
"changeFontSize()"
/>
<
input
type
=
"button"
value
=
"【obj.className】更改樣式"
onclick
=
"addRadius()"
/>
<
input
type
=
"button"
value
=
"更改外聯css樣式"
onclick
=
"recover()"
/>
</
div
>
</
div
>
|
方法一、使用obj.className來修改樣式表的類名
從下面的代碼可以看出ob.style.cssTest是如何來btnB的樣式的。
1
2
3
4
5
|
function
changeStyle1() {
var
obj = document.getElementById(
"btnB"
);
obj.style.backgroundColor=
"black"
;
}
|
該段代碼修改btB的文字的顏色,在瀏覽器中打開調試工具,可以發現btB標簽中多了一個屬性【style="內聯式>外聯式。而btB的hove偽類的background-color樣式寫在內聯式中,所以嵌入式的background-color覆蓋了偽類中,這就使得鼠標放入btB上感覺不到背景顏色的變化。
方法二、使用obj.style.cssTest來修改嵌入式的css
直接上JavaScript代碼:
1
2
3
4
5
|
function
changeStyle2() {
var
obj = document.getElementById(
"btnB"
);
obj.style.cssText = " display:block;color:White;
}
|
該段代碼和【一】中的效果是一樣的,缺陷也是一樣。
方法三、使用obj.className來修改樣式表的類名
使用代碼來修改btB引用樣式的類名,如下段代碼:
1
2
3
4
5
|
function
changeStyle3() {
var
obj = document.getElementById(
"btnB"
);
//obj.className = "style2";
obj.setAttribute(
"class"
,
"style2"
);
}
|
通過更改btB的css的類名的方式來更改樣式,更改樣式類名有兩種方式。1、obj.className = "style2"; 2、 obj.setAttribute("class", "style2");都是一樣的效果。
用這種方式來修改css比上面的效果要好很多。
方法四、使用更改外聯的css文件,從而改變元素的css
通過更改外聯的css文件引用從而來更改btB的樣式,操作很簡單。代碼如下:
首先得引用外聯的css文件,代碼如下:
1
2
3
4
5
6
|
<link href=
"css1.css"
rel=
"stylesheet"
type=
"text/css"
id=
"css"
/>
function
changeStyle4() {
var
obj = document.getElementById(
"css"
);
obj.setAttribute(
"href"
,
"css2.css"
);
}
|
這樣也能方便的更改btB的樣式,個人覺得這種方式是最好用的,是實現整體頁面換膚的最佳方案。