DIV CSS 佈局教程網

5.1 CSS 屬性操作:用 css() 直接控制樣式
編輯:jQuery基礎知識     

jQuery 操作元素樣式有兩條路:

  • (1)CSS 屬性操作;
  • (2)CSS 類名操作。

這一節先談前者。css() 是操作樣式最直接的工具,取值、設值都在同一支方法裡完成。

一、獲取 CSS 屬性值

語法:

$().css("屬性")

舉例:

 <!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
  p { color:Red; background-color:#F1F1F1; font-weight:bold; }
</style>
<script src="jquery-1.12.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function () {
    $("#btn").click(function () {
      var str = $("p").css("color");
      alert("p元素的color屬性值是:" + str);
    })
  })
</script>
</head>
<body>
  <p>學習網jQuery入門教程</p>
  <input id="btn" type="button" value="獲取"/>
</body>
</html>

分析:

$("#btn").click(function(){……}) 綁定的是滑鼠單擊事件,有 JavaScript 基礎的人一看就懂——這也是為什麼我一再強調,先把 JavaScript 打底再學 jQuery。事件處理的細節後續章節會專門講。

$("p").css("color") 讀取 p 元素的 color 值。點擊「獲取」後,瀏覽器會跳出對話框顯示結果:

二、設置 CSS 屬性值

設定樣式分兩種情況:設定單個屬性,以及一次設定多個屬性。

1、設置單個 CSS 屬性

語法:

$().css("屬性","屬性值")

舉例:

 <!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.12.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function () {
    $("#btn").click(function () {
      $("ul li:nth-child(odd)").css("color","red");
    })
  })
</script>
</head>
<body>
  <ul>
    <li>HTML</li>
    <li>CSS</li>
    <li>JavaScript</li>
    <li>jQuery</li>
    <li>ASP.NET</li>
  </ul>
  <input id="btn" type="button" value="設置" />
</body>
</html>

點擊前後的效果對比:

分析:

$("ul li:nth-child(odd)").css("color","red") 先用子元素偽類選擇器挑出 ul 底下奇數位置的 li,再把 color 設為 red。

2、設置多個 CSS 屬性

語法:

$().css({"屬性1":"屬性值1","屬性2":"屬性值2",……})

說明:

一次設定多個屬性時,要用 {} 把整組包起來,屬性與屬性值以「鍵值對」形式撰寫,每組之間用英文逗號分隔。這種寫法和 JSON 資料格式、JavaScript 物件字面值幾乎相同,學過就會覺得很順手。

實際上,單個屬性也可以用這種物件寫法表達,兩種形式可以互相替換。

舉例:

 <!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.12.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function () {
    $("#btn").click(function () {
      $("ul li:nth-child(odd)").css({"color":"red","background-color":"#F1F1F1"});
    })
  })
</script>
</head>
<body>
  <ul>
    <li>HTML</li>
    <li>CSS</li>
    <li>JavaScript</li>
    <li>jQuery</li>
    <li>ASP.NET</li>
  </ul>
  <input id="btn" type="button" value="設置" />
</body>
</html>

點擊前後的效果對比:

分析:

這裡一次替選到的元素套上多個 CSS 屬性,可讀性明顯比連續呼叫好。

補充一個等價寫法:

$("ul li:nth-child(odd)").css("color","red");

與下面這句效果相同:

$("ul li:nth-child(odd)").css({"color":"red"});
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved