jQuery css()方法

jQuery css()方法

jQuery CSS()方法用于获取(返回)或设置所选元素的样式属性或值。它方便您获取一个或多个样式属性。

jQuery CSS()方法提供两种方式:

1)返回一个CSS属性

它用于获取指定CSS属性的值。

语法

css("propertyname");

让我们举个例子来演示这个属性。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
(document).ready(function(){("button").click(function(){
        alert("Background color = " + $("p").css("background-color"));
    });
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style="background-color:#ff0000">The background-color of this paragraph is red.</p>
<p style="background-color:#00ff00">The background-color of this paragraph is green.</p>
<p style="background-color:#0000ff">The background-color of this paragraph is blue.</p>
<button>Click here to get the background-color of first matched element</button>
</body>
</html> 

注意:上面的例子会返回第一个匹配元素的背景颜色值。

2) 设置CSS属性

此属性用于为所有匹配元素设置特定的值。

语法

css("propertyname","value");   
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
(document).ready(function(){("button").click(function(){
        $("p").css("background-color", "violet");
    });
});
</script>
</head>
<body>
<p style="background-color:#ff0000">The background-color of this paragraph is red.</</p>
<p style="background-color:#00ff00">The background-color of this paragraph is green.</</p>
<p style="background-color:#0000ff">The background-color of this paragraph is blue.</</p>
<p>This paragraph has no background-color. </p>
<button>Click here to set a specific background-color of all matched element</button>
</body>
</html>

3)设置多个CSS属性

它只是设置CSS属性的扩展,它可以让你一次添加多个属性值。

语法:

css({"propertyname":"value","propertyname":"value",...});  

让我们举一个例子来展示这个属性。在这个例子中,我们为所有元素添加了两个属性:background-color和font-size。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
(document).ready(function(){("button").click(function(){
        $("p").css({"background-color": "yellow", "font-size": "200%"});
    });
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style="background-color:#ff0000">The background-color of this paragraph is red.</p>
<p style="background-color:#00ff00">The background-color of this paragraph is green.</p>
<p style="background-color:#0000ff">The background-color of this paragraph is blue.</p>
<p>This paragraph has no background-color.</p>
<button>Click here to set multiple styles for all selected elements.</button>
</body>
</html>

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程