jQuery css() 方法



jQuery 中的 css() 方法用於獲取設定所選元素的樣式屬性。

當用於返回屬性時,此方法返回第一個匹配元素的值。當用於設定屬性時,此方法將指定的 CSS 屬性分配給選擇中的每個匹配元素。

語法

我們有不同的語法來設定和獲取所選元素的一個或多個樣式屬性:

以下是返回 CSS 屬性值的語法

$(selector).css(property)

以下是設定 CSS 屬性和值的語法

$(selector).css(property,value)

以下是使用函式設定 CSS 屬性和值的語法

$(selector).css(property,function(index,currentvalue))

以下是設定多個屬性和值的語法

$(selector).css({property:value, property:value, ...})

引數

此方法接受以下引數:

  • property: 您想要設定的 CSS 屬性的名稱。
  • value: 您想要設定屬性的值。
  • function(index,currentvalue): 一個返回 CSS 屬性新值的函式。
    • index: 集合中元素的索引位置。
    • currentvalue: 元素的 CSS 屬性的當前值。

示例 1

在以下示例中,我們使用 css() 方法來設定所有 <p> 元素的 "background-color" 屬性:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("p").css("background-color", "yellow");
      });
    });
  </script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Change Color</button>
</body>
</html>

在執行按鈕後,背景顏色將新增到 DOM 中的所有 <p> 元素。

示例 2

在此示例中,我們為所有 <p> 元素設定多個 CSS 屬性:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("p").css({
          "color": "blue",
          "background-color": "yellow"
        });
      });
    });
  </script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Change Styles</button>
</body>
</html>

當我們點選按鈕時,提供的屬性將新增到所有 <p> 元素。

示例 3

在這裡,我們使用 css() 方法返回元素的 CSS 屬性:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        var color = $("p:first").css("background-color");
        alert("The color of the first paragraph is: " + color);
      });
    });
  </script>
</head>
<body>
<p style="background-color: yellow;">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Get Color</button>
</body>
</html>

執行上述程式後,它會顯示第一段的當前背景顏色。

示例 4

在下面的示例中,我們使用 css() 方法的函式引數來設定 CSS 屬性:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("p").css("font-size", function(index, currentValue){
          return parseFloat(currentValue) + 2 + "px";
        });
      });
    });
  </script>
</head>
<body>
<p style="font-size: 14px;">This is a paragraph.</p>
<p style="font-size: 16px;">This is another paragraph.</p>
<button>Increase Font Size</button>
</body>
</html>

當我們點選按鈕時,它會將每一段的字型大小增加 2px。

jquery_ref_html.htm
廣告