jQuery css methods
jQuery css() method
css() method sets or returns one or more style properties of the selected element.
Return CSS properties
To return the value of the specified CSS property, please use the following syntax:
css("propertyname");
The following example will return the background-color value of the first matching element:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ alert("背景顏色 = " + $("p").css("background-color")); }); }); </script> </head> <body> <h2>這是一個(gè)標(biāo)題</h2> <p style="background-color:#ff0000">這是一個(gè)段落。</p> <p style="background-color:#00ff00">這是一個(gè)段落。</p> <p style="background-color:#0000ff">這是一個(gè)段落。</p> <button>返回 p 元素的 background-color </button> </body> </html>
Run the program to try it
Set CSS properties
To set the specified CSS properties, please use the following syntax:
css("propertyname","value");
The following example will set the background-color value for all matching elements:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css("background-color","yellow"); }); }); </script> </head> <body> <h2>這是一個(gè)標(biāo)題</h2> <p style="background-color:#ff0000">這是一個(gè)段落。</p> <p style="background-color:#00ff00">這是一個(gè)段落。</p> <p style="background-color:#0000ff">這是一個(gè)段落。</p> <p>這是一個(gè)段落。</p> <button>設(shè)置 p 元素的 background-color </button> </body> </html>
Run the program to try it
Set multiple CSS properties
If you need to set multiple CSS properties, please use the following syntax:
css({"propertyname":"value","propertyname":"value",...});
The following example will set the background-color and font-size for all matching elements :
##Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css({"background-color":"yellow","font-size":"150%"}); }); }); </script> </head> <body> <h2>這是一個(gè)標(biāo)題</h2> <p style="background-color:#ff0000">這是一個(gè)段落。</p> <p >這是一個(gè)段落。</p> <p style="background-color:#0000ff">這是一個(gè)段落。</p> <p>這是一個(gè)段落。</p> <button>為 p 元素設(shè)置多個(gè)樣式</button> </body> </html>Run the program and try it