.css()


取得匹配元素集合中第一個元素的計算樣式屬性,或為每個匹配元素設定一個或多個 CSS 屬性。

.css( propertyName )傳回:字串

說明:取得匹配元素集合中第一個元素的計算樣式屬性。

.css() 方法是一種從第一個匹配的元素中取得計算樣式屬性的便利方式,特別是在考量到不同瀏覽器存取大多數這些屬性的不同方式(基於標準的瀏覽器中的 getComputedStyle() 方法,相對於 Internet Explorer 9 之前的版本中的 currentStyleruntimeStyle 屬性)以及不同瀏覽器對特定屬性使用的不同術語時。例如,Internet Explorer 的 DOM 實作將 float 屬性稱為 styleFloat,而符合 W3C 標準的瀏覽器將其稱為 cssFloat。為了保持一致性,你可以簡單地使用 "float",而 jQuery 會將其轉換為每個瀏覽器的正確值。

此外,jQuery 可以平等地解析多個單字屬性的 CSS 和 DOM 格式。例如,jQuery 了解並傳回 .css( "background-color" ).css( "backgroundColor" ) 的正確值。這表示混合大小寫具有特殊意義,例如,.css( "WiDtH" ) 執行的動作與 .css( "width" ) 不同。

請注意,元素的計算樣式可能與樣式表中為該元素指定的數值不同。例如,維度的計算樣式幾乎總是像素,但它們可以在樣式表中指定為 em、ex、px 或 %。不同的瀏覽器可能會傳回邏輯上相等但文字上不相等的 CSS 顏色值,例如 #FFF、#ffffff 和 rgb(255,255,255)。

擷取簡寫 CSS 屬性(例如,marginbackgroundborder),儘管在某些瀏覽器中具有功能,但並非有保證的。例如,如果你要擷取已呈現的 border-width,請使用:$( elem ).css( "borderTopWidth" )$( elem ).css( "borderBottomWidth" ),依此類推。

在元素上呼叫 .css() 時,該元素應連接到 DOM。如果沒有,jQuery 可能會擲回錯誤。

從 jQuery 1.9 開始,傳遞樣式屬性陣列給 .css() 將會產生屬性值配對的物件。例如,若要擷取所有四個已呈現的 border-width 值,您可以使用 $( elem ).css([ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth" ])

從 jQuery 3.2 開始,支援 CSS 自訂屬性(也稱為 CSS 變數):$( "p" ).css( "--custom-property" )。請注意,您需要按原樣提供屬性名稱,使用駝峰式大小寫對其進行轉換無法像一般 CSS 屬性那樣運作。

範例

取得已按一下 div 的背景顏色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
div {
width: 60px;
height: 60px;
margin: 5px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<span id="result">&nbsp;</span>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>
<script>
$( "div" ).on( "click", function() {
var color = $( this ).css( "background-color" );
$( "#result" ).html( "That div is <span style='color:" +
color + ";'>" + color + "</span>." );
});
</script>
</body>
</html>

示範

取得已按一下 div 的寬度、高度、文字顏色和背景顏色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
div {
height: 50px;
margin: 5px;
padding: 5px;
float: left;
}
#box1 {
width: 50px;
color: yellow;
background-color: blue;
}
#box2 {
width: 80px;
color: rgb(255, 255, 255);
background-color: rgb(15, 99, 30);
}
#box3 {
width: 40px;
color: #fcc;
background-color: #123456;
}
#box4 {
width: 70px;
background-color: #f11;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p id="result">&nbsp;</p>
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<script>
$( "div" ).on( "click", function() {
var html = [ "The clicked div has the following styles:" ];
var styleProps = $( this ).css([
"width", "height", "color", "background-color"
]);
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
$( "#result" ).html( html.join( "<br>" ) );
});
</script>
</body>
</html>

示範

.css( propertyName, value )傳回:jQuery

說明:設定一或多個 CSS 屬性,以符合元素的集合。

.prop() 方法一樣,.css() 方法讓設定元素屬性變得快速又容易。此方法可以將屬性名稱和值作為個別參數,或作為單一鍵值配對物件。

此外,jQuery 可以同樣詮釋多字元屬性的 CSS 和 DOM 格式。例如,jQuery 可以理解並傳回 .css({ "background-color": "#ffe", "border-left": "5px solid #ccc" }).css({backgroundColor: "#ffe", borderLeft: "5px solid #ccc" }) 的正確值。請注意,使用 DOM 表示法時,屬性名稱周圍的引號是選用的,但使用 CSS 表示法時,由於名稱中有連字號,因此是必要的。

當數字傳遞為值時,jQuery 會將其轉換為字串,並在該字串的結尾加上 px。如果屬性需要單位,除了 px 之外,請在呼叫方法之前將值轉換為字串並加上適當的單位。

在將 .css() 用作設定器時,jQuery 會修改元素的 style 屬性。例如,$( "#mydiv" ).css( "color", "green" ) 等同於 document.getElementById( "mydiv" ).style.color = "green"。將樣式屬性的值設定為空字串(例如 $( "#mydiv" ).css( "color", "" ))會從元素中移除該屬性(如果已直接套用),無論是在 HTML 樣式屬性中、透過 jQuery 的 .css() 方法,或透過直接 DOM 操作 style 屬性。因此,該屬性的元素樣式將會回復到套用任何值的狀態。因此,此方法可取消您先前執行的任何樣式修改。不過,它不會移除已在樣式表或 <style> 元素中使用 CSS 規則套用的樣式。警告:一個值得注意的例外是,對於 IE 8 及以下版本,移除 borderbackground 等速記屬性會完全從元素中移除該樣式,無論在樣式表或 <style> 元素中設定為何。

注意:.css() 不支援 !important 宣告。因此,陳述式 $( "p" ).css( "color", "red !important" ) 截至 jQuery 3.6.0 並不會將頁面中所有段落的顏色變為紅色。不過,請勿依賴於「不起作用」,因為未來版本的 jQuery 可能會加入對此類宣告的支援。強烈建議改用類別;否則,請使用 jQuery 外掛程式。

從 jQuery 1.8 開始,.css() 設定器會自動處理屬性名稱的前綴。例如,在 Chrome/Safari 中使用 .css( "user-select", "none" ) 會將其設定為 -webkit-user-select,Firefox 會使用 -moz-user-select,而 IE10 會使用 -ms-user-select

從 jQuery 1.6 開始,.css() 接受與 .animate() 類似的相對值。相對值是一個以 +=-= 開頭的字串,用於增加或減少目前的值。例如,如果元素的 padding-left 為 10px,.css( "padding-left", "+=15" ) 會導致 padding-left 總計為 25px。

從 jQuery 1.4 開始,.css() 允許我們傳遞一個函式作為屬性值

1
2
3
$( "div.example" ).css( "width", function( index ) {
return index * 50;
});

這個範例將匹配元素的寬度設定為遞增更大的值。

注意:如果設定函式中沒有傳回任何東西(例如 function( index, style ){} ),或傳回 undefined,則不會變更目前的值。這對於僅在符合特定條件時選擇性設定值很有用。

從 jQuery 3.2 開始,支援 CSS 自訂屬性(也稱為 CSS 變數):$( "p" ).css( "--custom-property", "value" )。請注意,您需要按原樣提供屬性名稱,使用駝峰式大小寫無法像一般 CSS 屬性一樣運作。

範例

在滑鼠移入事件中將任何段落的顏色變為紅色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
p {
color: blue;
width: 200px;
font-size: 14px;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p>Just roll the mouse over me.</p>
<p>Or me to see a color change.</p>
<script>
$( "p" ).on( "mouseover", function() {
$( this ).css( "color", "red" );
});
</script>
</body>
</html>

示範

在第一次按一下 #box 時增加其寬度 200 個像素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
#box {
background: black;
color: snow;
width: 100px;
padding: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div id="box">Click me to grow</div>
<script>
$( "#box" ).one( "click", function() {
$( this ).css( "width", "+=200" );
});
</script>
</body>
</html>

示範

在段落中反白按一下的字詞。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
p {
color: blue;
font-weight: bold;
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p>
Once upon a time there was a man
who lived in a pizza parlor. This
man just loved pizza and ate it all
the time. He went on to be the
happiest man in the world. The end.
</p>
<script>
var words = $( "p" ).first().text().split( /\s+/ );
var text = words.join( "</span> <span>" );
$( "p" ).first().html( "<span>" + text + "</span>" );
$( "span" ).on( "click", function() {
$( this ).css( "background-color", "yellow" );
});
</script>
</body>
</html>

示範

在滑鼠移入和滑鼠移出時變更字體粗細和背景顏色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
p {
color: green;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p>Move the mouse over a paragraph.</p>
<p>Like this one or the one above.</p>
<script>
$( "p" )
.on( "mouseenter", function() {
$( this ).css({
"background-color": "yellow",
"font-weight": "bolder"
});
})
.on( "mouseleave", function() {
var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$( this ).css( styles );
});
</script>
</body>
</html>

示範

在按一下 div 時增加其大小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
div {
width: 20px;
height: 15px;
background-color: #f33;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div>click</div>
<div>click</div>
<script>
$( "div" ).on( "click", function() {
$( this ).css({
width: function( index, value ) {
return parseFloat( value ) * 1.2;
},
height: function( index, value ) {
return parseFloat( value ) * 1.2;
}
});
});
</script>
</body>
</html>

示範