如何点击隐藏和显示一个div:
在很多时候有这样的需求,那就是点击显示一个div,再点击就会隐藏显示的div。例如在网站后台添加文章的时候,有时候会根据用户的需要选择是否添加额外的信息。下面就简单介绍一下如何实现此种效果。
实现点击隐藏和显示div的方法有多种,下面就介绍一下比较常用的一种:
使用toggle()方法实现div的隐藏隐藏和显示,代码实例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<style type="text/css">
body{
color:#666;
font-family:Verdana, Geneva, sans-serif;
font-size:12px;
}
.msgtable th{
background: url(mytest/jQuery/table_th_bg.gif) repeat-x bottom;
}
.msgtable td{
padding:0.4em;
border-bottom:1px solid #F3F3F3;
}
.input{
padding:0px 3px;
border:1px solid #d1d1d1;
background:url(mytest/jQuery/input_bg.jpg) repeat-x;
height:18px;
line-height:18px;
font-size:12px;
color:#999;
}
.up-01{
background: url(mytest/jQuery/top_ico1.gif) no-repeat 0 center;
}
.up-02{
background: url(mytest/jQuery/top_ico2.gif) no-repeat 0 center;
}
.up-01, .up-02{
display:block;
float:right;
padding-left:20px;
cursor:pointer;
line-height:17px;
}
.hide{display: none;}
.textarea {
padding:3px;
border:1px solid #d1d1d1;
background:url(mytest/jQuery/input_bg.jpg) repeat-x;
font-size:12px;
color:#999;
}
.w250{width:250px;}
.w380{width:380px;}
.wh380{
width:380px;
height:50px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#upordown").toggle(function(){
$(this).text("关闭高级设置");
$(this).removeClass();
$(this).addClass("up-01");
$(".upordown").show();
},function(){
$(this).text("显示高级设置");
$(this).removeClass();
$(this).addClass("up-02");
$(".upordown").hide();
})
})
</script>
</head>
<body>
<table width="650" border="0" cellspacing="0" cellpadding="0" class="msgtable">
<tr>
<th colspan="2" align="left">发布资讯</th>
</tr>
<tr>
<td width="15%" align="right">文章标题:</td>
<td width="85%"><input type="text" class="input w380" /></td>
</tr>
<tr>
<td align="right">文章作者:</td>
<td><input type="text" class="input w250" /></td>
</tr>
<tr>
<td align="right">文章来源:</td>
<td><input type="text" class="input w250" />
<span id="upordown" class="up-02">显示高级选项</span></td>
</tr>
<tr class="upordown hide">
<td align="right">Meta关键字:</td>
<td><input type="text" class="input w250" /></td>
</tr>
<tr class="upordown hide">
<td align="right">Meta描述:</td>
<td><textarea class="textarea wh380"></textarea></td>
</tr>
<tr class="upordown hide">
<td align="right">文章导读:</td>
<td><textarea class="textarea wh380"></textarea></td>
</tr>
</table>
</body>
</html>
以上代码是在后台添加文章时候非常常见的一个功能,通过使用toggle()方法,来实现当点击span元素的时候切换执行toggle()方法中的两个函数。两个函数分别用来替换span中的文本和span元素的背景图片以及class为upordown的行隐藏和显示。
最为原始地址是:http://www.softwhy.com/