jQuery - CSS 屬性



jQuery 提供了 `css()` 方法來操作匹配元素的 CSS 屬性。

jQuery `css()` 方法不會修改 jQuery 物件的內容,但它們用於獲取和設定 DOM 元素上的 CSS 屬性。

jQuery - 獲取 CSS 屬性

jQuery `css()` 方法可以用來獲取與第一個匹配的 HTML 元素關聯的 CSS 屬性的值。以下是 `css()` 方法的語法:

$(selector).css(propertyName);

jQuery 理解並返回 `css( "background-color" )` 和 `css( "backgroundColor" )` 的正確值。

示例

讓我們嘗試以下示例並驗證結果。這應該返回第一個匹配的 <div> 的背景顏色。

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         alert("Background color = " + $("div").css("background-color"));
      });
   });
</script>
<style>
   button{margin:10px;width:150px;cursor:pointer}
   div{ margin:10px;padding:12px; width:125px;}
</style>
</head>
<body>
   <p>Click the below button to see the result:</p>

   <div style="background-color:#9c9cff;">Blue</div>
   <div style="background-color:#93ff93;">Green</div>

   <button>Get CSS Property</button>
</body>
</html>

jQuery - 設定 CSS 屬性

jQuery `css()` 方法可以用來設定與匹配的 HTML 元素關聯的一個或多個 CSS 屬性的值。以下是 `css()` 方法的語法:

$(selector).css(propertyName, value);

這裡兩個引數都是必需的,`propertyName` 表示 CSS 屬性名,而 `value` 表示屬性的有效值。

示例

讓我們嘗試以下示例並驗證結果。這裡我們將獲取第一個匹配的 <div> 的顏色,並將所有 <p> 的文字顏色更改為 div 的背景顏色。

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         var color = $("div").css("background-color");
         $("p").css("color", color);
      });
   });
</script>
<style>
   button{margin:10px;width:150px;cursor:pointer}
   div{ margin:10px;padding:12px; width:125px;}
</style>
</head>
<body>
   <p>Click the below button to see the result:</p>

   <div style="background-color:#9c9cff;">Blue</div>
   <div style="background-color:#93ff93;">Green</div>

   <button>Set CSS Property</button>
</body>
</html>

jQuery - 設定多個 CSS 屬性

您可以使用單個 jQuery 方法 `css()` 在匹配的元素上應用多個 CSS 屬性。您可以在一次呼叫中應用任意數量的屬性。

以下是使用 `css()` 方法設定多個 CSS 屬性的語法:

$(selector).css({propertyName1:value1, propertyName2:value2,...});

示例

讓我們嘗試以下示例並驗證結果。這裡我們將所有 <div> 的背景顏色設定為 "#fb7c7c;",字型大小設定為 25px。

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $("div").css({"background-color":"#fb7c7c", "font-size": "25px"});
      });
   });
</script>
<style>
   button{margin:10px;width:150px;cursor:pointer}
   div{ margin:10px;padding:12px; width:125px;}
</style>
</head>
<body>
   <p>Click the below button to see the result:</p>

   <div style="background-color:#9c9cff;">Blue</div>
   <div style="background-color:#93ff93;">Green</div>

   <button>Set CSS Property</button>
</body>
</html>

jQuery HTML/CSS 參考

您可以在以下頁面獲取操作 CSS 和 HTML 內容的所有 jQuery 方法的完整參考:jQuery HTML/CSS 參考

廣告