Javascript点击显示或隐藏下拉框

效果图:

代码:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>JS点击显示或隐藏下拉框</title>
 6 <style type="text/css">
 7     html,body,div,ul,li{padding: 0;margin: 0;}
 8     li{list-style: none;}
 9     a{text-decoration: none;color: #ccc;font-size: 13px;}
10     #top{width: 100%;background: #2D2D2D;height: 30px;}
11     .topli{float: left;height: 30px;line-height: 30px;}
12     .topli a{display:block;padding: 0 14px;height: 30px;}
13     .topli a:hover{background:#444;}
14     .more{position: absolute;top: 30px;background: #fff;display: none;border: 1px solid #c2c2c2;z-index: 999;border-top: none;}
15     .more a{color: #3366CC;}
16     .more a:hover{background: #f0f0f0;}
17 </style>
18 <script type="text/javascript">
19     function moreCon(){
20         var backg = document.getElementById('colorChange');  //定义变量
21         var mdiv = document.getElementById('moreContent');
22         if (mdiv.style.display=='block') {                  //if else判断ID为moreContent的display是否为block   “==”为“等于” 为比较运算符
23             mdiv.style.display='none';
24             backg.style.background='#2D2D2D';                //修改样式
25             backg.style.color='#ccc';
26         }
27         else
28             {
29                 mdiv.style.display='block';
30                 backg.style.background='#fff';
31                 backg.style.color='#3366CC';
32             }
33     }
34 </script>
35 <!-- JS点击显示或隐藏下拉框 end -->
36 </head>
37 <body>
38 <ul id="top">
39     <li class="topli"><a href="">搜索</a></li>
40     <li class="topli"><a href="">图片</a></li>
41     <li class="topli"><a href="">地图</a></li>
42     <li class="topli"><a href="">新闻</a></li>
43     <li class="topli">
44         <a href="javascript:void()" onclick="moreCon()" id="colorChange">更多</a>
45         <!-- 对于浏览器来说  onclick会比href先执行 -->
46         <div class="more" id="moreContent">
47             <ul>
48                 <li><a href="">云端硬盘</a></li>
49                 <li><a href="">日历</a></li>
50                 <li><a href="">翻译</a></li>
51                 <li><a href="">Blogger</a></li>
52             </ul>
53         </div>
54     </li>
55 </ul>
56 </body>
57 </html>

知识点:

1、if条件语句  详细介绍与实例:http://www.w3school.com.cn/js/js_if_else.asp

2、js的比较运算符:“==”为“等于”,“===”为“完全相等(值和类型)”,详细参考:http://www.w3school.com.cn/js/js_comparisons.asp

3、a的“href”与“onclick”:浏览器会先执行onclick事件,在执行href属性下的动作。为了保持href的css样式,又不会影响onclick事件,可以写成

 <a href="javascript:void()" onclick="moreCon()" id="colorChange">更多</a>

 

 

posted @ 2013-12-26 16:26  cubepuss  阅读(1757)  评论(0)    收藏  举报