jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:
下面的样式表将用于本页的所有例子:
.important |
{ |
font-weight:bold; |
font-size:xx-large; |
} |
.blue |
{ |
color:blue ; |
} |
下面的例子展示如何向不同的元素添加 class 属性。当然,在添加类时,您也可以选取多个元素:
<!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(){ |
$("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>标题 1</h1> |
<h2>标题 2</h2> |
<p>这是一个段落。</p> |
<p>这是另外一个段落。</p> |
<div>这是一些重要的文本!</div> |
<br> |
<button>为元素添加 class</button> |
</body> |
</html> |
$("button").click(function(){ |
$("#div1").addClass("important blue"); |
}); |
下面的例子演示如何在不同的元素中删除指定的 class 属性:
<!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(){ |
$("h1,h2,p").removeClass("blue"); |
}); |
}); |
</script> |
<style type="text/css"> |
.important |
{ |
font-weight:bold; |
font-size:xx-large; |
} |
.blue |
{ |
color:blue ; |
} |
</style> |
</head> |
<body> |
<h1 class="blue">标题 1</h1> |
<h2 class="blue">标题 2</h2> |
<p class="blue">这是一个段落。</p> |
<p>这是另外一个段落。</p> |
<br> |
<button>从元素中移除 class</button> |
</body> |
</html> |
下面的例子将展示如何使用 jQuery toggleClass() 方法。该方法对被选元素进行添加/删除类的切换操作:
<!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(){ |
$("h1,h2,p").toggleClass("blue"); |
}); |
}); |
</script> |
<style type="text/css"> |
.blue |
{ |
color:blue ; |
} |
</style> |
</head> |
<body> |
<h1 class="blue">标题 1</h1> |
<h2 class="blue">标题 2</h2> |
<p class="blue">这是一个段落。</p> |
<p>这是另外一个段落。</p> |
<br> |
<button>切换 class</button> |
</body> |
</html> |
我们将在下一章讲解 jQuery css() 方法。