jQuery - css() 方法

来源:互联网 发布:beats蓝牙耳机连接mac 编辑:程序博客网 时间:2024/05/21 19:41

jQuery css() 方法

css() 方法设置或返回被选元素的一个或多个样式属性。

返回 CSS 属性

如需返回指定的 CSS 属性的值,请使用如下语法:

css("propertyname");

下面的例子将返回首个匹配元素的 background-color 值:

实例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script src="jquery.js"></script></head><body><h2>标题</h2><p style="background-color:#F00;">第一段落</p><p style="background-color:#0F0">第二段落</p><p style="background-color:#00F;">第三段落</p><button>返回 p 元素值</button><script>$(document).ready(function(){$("button").click(function(){alert("background-color = " + $("p").css("background-color"));})})</script></body></html>
效果图:


设置 CSS 属性

如需设置指定的 CSS 属性,请使用如下语法:

css("propertyname","value");

下面的例子将为所有匹配元素设置 background-color 值:

实例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script src="jquery.js"></script></head><body><h2>标题</h2><p style="background-color:#F00;">第一段落</p><p style="background-color:#0F0">第二段落</p><p style="background-color:#00F ;">第三段落</p><p>第四个段落</p><button>改变回 p 元素值</button><script>$(document).ready(function(){$("button").click(function(){$("p").css("background-color","#0FF");});});</script></body></html>
效果图:

设置多个 CSS 属性

如需设置多个 CSS 属性,请使用如下语法:

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

下面的例子将为所有匹配元素设置 background-color 和 font-size:

实例

<script>$(document).ready(function(){  $("button").click(function(){    $("p").css({"background-color":"yellow","font-size":"200%"});  });});</script>
0 0
原创粉丝点击