這節課,我們看下如果使用jq的css操作方法。
你可以先運作下下面的代碼,比較下jq與傳統操作方式的差别:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>jQuery一點一滴系列教程(第二滴)</title>
<style type="text/css">
li
{
color:#369;
}
.current
color:#f90;
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
//傳統方式,需要寫更多的代碼
/*var theItem=document.getElementsByTagName("li")[0];
if(theItem.currentStyle)
alert(theItem.currentStyle.color);
else if(window.getComputedStyle)
alert(window.getComputedStyle(theItem,null).color);*/
alert($("li").css("color"));//擷取第一個Li的color屬性值
});
</script>
</head>
<body>
<ul>
<li>第一行</li>
<li class="current">第二行</li>
<li>第三行</li>
<li>第四行</li>
<li>第五行</li>
</ul>
</body>
</html>
注意jq的元素選擇方式(選擇器),和css的類似,可以自己比較下。
$("li")通路文檔中的li元素,不管什麼嵌套層次;
當然了選擇類可以這樣$(".current"),如果選擇ID的就是$("#myId")等。
這是擷取css屬性值,也可以設定,如下:
$(function(){
//傳統方式,需要寫更多的代碼
/*var theItem=document.getElementsByTagName("li")[0];
if(theItem.currentStyle)
alert(theItem.currentStyle.color);
else if(window.getComputedStyle)
alert(window.getComputedStyle(theItem,null).color);*/
//alert($("li").css("color"));//擷取第一個Li的color屬性值
$("ul").click(function(){
$("li").css("color","#900");
});
是不是很簡單啊。
當然了另外一個重載的方式是傳入對象:
$("li").css({color:"090",backgroundColor:"#f0f0ff"});
這樣單擊ul後,發現樣式的變化。
還有一種通過函數計算傳回值作為屬性值的:
$("li").css("backgroundColor",function(index,value){var clr=index*80;return "rgb("+clr+","+clr+","+clr+")";});
翻來覆去就是css()的變種,簡單吧?
本文轉自 xcf007 51CTO部落格,原文連結:http://blog.51cto.com/xcf007/355229,如需轉載請自行聯系原作者