jQuery 入门教程(17): 读写HTML元素的css 属性

jerry JQuery 2015年08月24日 收藏

jQuery 的css()方法用来设置或读取HTML元素的css属性。
读取元素的CSS语法语法如下:
css(“propertyname“);
比如下面代码取得第一个<p>元素的背景颜色。

  1. $("p").css("background-color");

使用下面的语法来设置HTML元素的CSS属性:

css(“propertyname“,”value“);

例如,下面代码为所有<p>元素设置背景色为黄色。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JQuery Demo</title>
  6. <script src="scripts/jquery-1.9.1.js"></script>
  7. <script>
  8. $(document).ready(function () {
  9. $("button").click(function () {
  10. $("p").css("background-color", "yellow");
  11. });
  12. });
  13. </script>
  14. </head>
  15.  
  16. <body>
  17. <h2>This is a heading</h2>
  18. <p style="background-color: #ff0000">This is a paragraph.</p>
  19. <p style="background-color: #00ff00">This is a paragraph.</p>
  20. <p style="background-color: #0000ff">This is a paragraph.</p>
  21. <p>This is a paragraph.</p>
  22. <button>Set background-color of p</button>
  23. </body>
  24. </html>

20130309008
css()也支持同时多个CSS属性:其语法如下:
css({“propertyname“:”value“,”propertyname“:”value“,…});
比如:

  1. $("p").css({"background-color":"yellow","font-size":"200%"});