jQuery 支持方法用來(lái)操作 HTML 元素的 CSS 屬性
下面的方法為 jQuery 提供的 CSS 操作方法:
下面的 StyleSheet 為后面例子使用的 CSS 風(fēng)格:
.important
{
font-weight:bold;
font-size:xx-large;
}
.blue
{
color:blue;
}
jQuery addClass 示例
下面的例子為給定的元素添加 CSS 風(fēng)格類(lèi)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery Demo</title>
<script src="scripts/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
});
});
</script>
<style type="text/css">
.important
{
font-weight: bold;
font-size: xx-large;
}
.blue
{
color: blue;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<div>This is some important text!</div>
<br>
<button>Add classes to elements</button>
</body>
</html>
http://wiki.jikexueyuan.com/project/jquery-tutorial/images/11.png" alt="" />
你也可以在 addClass 添加多個(gè)類(lèi)的名稱(chēng),如:
$("button").click(function(){
$("#div1").addClass("important blue");
});
jQuery removeClass 示例
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
jQuery toggle()示例,下面的例子使用 toggle 為 HTML 元素在添加/刪除 CSS 類(lèi) blue 之間切換
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
下一篇介紹 css()的用法。