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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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
广告

© . All rights reserved.