本文概述
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属性
它只是Set 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>
立即测试
输出:
本段的背景颜色为红色。
本段的背景颜色为绿色。
本段的背景颜色为蓝色。
单击此处为所有选定的元素设置多种样式。
评论前必须登录!
注册