jQuery 操作元素樣式有兩條路:
這一節先談前者。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("屬性","屬性值")
舉例:
<!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。
語法:
$().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"});