您的位置:首页 > Web前端 > JQuery

jQuery一点一滴系列教程(第二滴)

2010-07-22 15:53 218 查看
这节课,我们看下如果使用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");

});

});

是不是很简单啊。

当然了另外一个重载的方式是传入对象:

$("ul").click(function(){

$("li").css({color:"090",backgroundColor:"#f0f0ff"});

});

这样单击ul后,发现样式的变化。

还有一种通过函数计算返回值作为属性值的:

$("ul").click(function(){

$("li").css("backgroundColor",function(index,value){var clr=index*80;return "rgb("+clr+","+clr+","+clr+")";});

});

翻来覆去就是css()的变种,简单吧?

本文出自 “HOHO网页设计” 博客,请务必保留此出处http://xcf007.blog.51cto.com/471707/355229
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: