jquery是完全支援css的,我們舉個例子來看看使用jquery的方便之處,這功勞是屬於選擇器的:
例1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function()
{
$("li.abc").css("color","red");
});
</script>
</head>
<body>
<div id="hello">
<ul>
<li>niujiabin</li>
<li class="abc">maybe</li>
<li>gossipgo</li>
</ul>
</div>
</body>
</html>
我們想要做到改變maybe字型顏色為紅色
$("li.abc")
利用選擇器可以直接獲取到,非常方便,如果利用javascript獲取就很麻煩
.css("color","red");
<li>之間的文字就會變成紅色
執行結果:
例2:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function()
{
$("#hello ul li:even").css("background","grey").css("color","red");
});
</script>
</head>
<body>
<div id="hello">
<ul>
<li>niujiabin</li>
<li class="abc">maybe</li>
<li>gossipgo</li>
</ul>
</div>
</body>
</html>
$("#hello ul li:even")
選取id為hello下的ul下的li的奇數行。
.css("color","red");
改變奇數行的顏色
執行結果:
例3:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.bg{
background:#f00;
color:#fff;
}
</style>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function()
{
$("li").mouseover(setColor).mouseout(setColor);
function setColor()
{
$(this).toggleClass("bg");
}
});
</script>
</head>
<body>
<div id="hello">
<ul>
<li>niujiabin</li>
<li class="abc">maybe</li>
<li>gossipgo</li>
</ul>
</div>
</body>
</html>
<style type="text/css">
.bg{
background:#f00;
color:#fff;
}
</style>
css樣式,設定背景色和顏色
$("li").mouseover(setColor).mouseout(setColor);
為li新增事件
執行結果是滑鼠放到哪就會顯示變化,離開就會消失。