显示和隐藏下拉菜单中的JavaScript函数

时间:2015-03-11 17:26:20

标签: javascript html css

我正在尝试为我正在处理的网站创建一个下拉菜单,我在隐藏和显示我使用过的代码下拉时遇到了问题。

基本上,我需要这个:

<a href="#"  onclick="showHide('collections'); return false;">The Collections</a>

在浏览器中阅读:

<a href="#" style="display:block">The Collections</a>

或显示

<a href="#" style="display:none">The Collections</a>

代码:

<html>
<head>
    <title>Menu Test</title>
    <!-- Begin css library -->
        <style type="text/css">
            html {
                overflow-y: scroll;
                margin: 0;
                padding: 0;
                font-family: sans-serif;
            }

            body {
                background-color: #fff;
                color: #444;
                margin: 0px;
                padding: 0px;
            }

            /* Begin top bar 
                *************************/
            #top-bar {
                -webkit-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);
                -moz-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);
                box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);
                font-family: GillSansMTStd-Book;
            }
            #top-bar-content {
                position: relative;
                height: 94px;
                margin: 0 auto;
                width: 1025px;
                text-align: "right";
            }

            #top-bar .wrap {
                padding-left: 33px;
                padding-right: 33px;
            }

            #top-bar .links {
                float: right;
                line-height: 94px;
            }

            #top-bar a {
                outline:0;  
            }

            #top-bar .links a {
            display: inline-block;
            color: #b9afa3;
            font-size: 14px;
            font-weight: normal;
            letter-spacing: .8px;
            text-decoration: none;
            margin-left: 30px;
            text-transform: uppercase;
            }

            #top-bar .links a:hover,
            #top-bar .links a.active {
            color: #746758;
            background: url(/HalstedDesigns/catalog/view/theme/margaretha/image/nav-rule.gif) top center no-repeat;
            }

            #top-bar .collections {
                display: none;
                background-color: #695d4f;
                color: #fff;
                position: absolute;
                top: 94px;
                width: 340px;
                text-align: center;
                margin-left: 80px;
                padding-top: 10px;
                -webkit-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);
                -moz-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);
                box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);
                z-index: 5;
            }

            #top-bar .collections a{
                color:#fff;
                display:block;
                line-height:26px;
                padding:10px 20px;
                margin:0;
                background-image:none;
                text-transform:capitalize;
                font-size:16px;
            }

            #top-bar .collections a.the-ardmore-collection {
                font-size:14px;
            }

            #top-bar .collections a:hover,
            #top-bar .collections a.active {
                background-color:#fff;
                color:#695d4f;
                background-image:none;
            }
        </style>
    <!-- End css library -->

    <!-- Begin jquery library -->
        <script language="javascript" type="text/javascript">
            function showHide(shID) {
                if (document.getElementById(shID)) {
                    if (document.getElementById(shID+'-show').style.display != 'none') {
                        document.getElementById(shID+'-show').style.display = 'block';
                        document.getElementById(shID).style.display = 'block';
                    }
                    else {
                        document.getElementById(shID+'-show').style.display = 'none';
                        document.getElementById(shID).style.display = 'none';
                    }
                }
            }
        </script>
    <!-- End jquery library -->
</head>
<body>
    <div id="top-bar">
        <div id="top-bar-content">
            <div class="wrap">
                <a href="/" title="Home" float="left"><img src="image/halsted-logo.png"; alt="Halsted Logo"></a>
                <div class="links">
                <div class="collections">
                    <a href="http://halsteddesign.com/the-ardmore-collection/" class="the-ardmore-collection font-gillsans ">THE ARDMORE COLLECTION</a>                
                    <a href="http://halsteddesign.com/the-ardmore-collection/qalakabusha-sofa" class="lusitanaregular">Qalakabusha Sofa</a>      
                    <a href="http://halsteddesign.com/the-ardmore-collection/qalakabusha-fabric-collection" class="lusitanaregular">Qalakabusha Fabric Collection</a>        
                    <a href="http://halsteddesign.com/the-ardmore-collection/hand-bags" class="lusitanaregular">Hand bags</a>          
                    <a href="http://halsteddesign.com/the-ardmore-collection/scatter-cushions" class="lusitanaregular">Scatter Cushions</a>         
                    <a href="http://halsteddesign.com/the-ardmore-collection/batonka-stools" class="lusitanaregular">Batonka Stools</a>           
                    <a href="http://halsteddesign.com/the-ardmore-collection/tablecloths" class="lusitanaregular">Tablecloths</a>         
                    <a href="http://halsteddesign.com/the-ardmore-collection/place-mats" class="lusitanaregular">Place Mats</a>       
                    <a href="http://halsteddesign.com/the-ardmore-collection/napkins" class="lusitanaregular">Napkins</a>         
                    <a href="http://halsteddesign.com/the-ardmore-collection/table-runners" class="lusitanaregular">Table Runners</a>
                </div>              
                    <a href="http://halsteddesign.com">Art Into Design</a>        
                    <a href="#"  onclick="showHide('collections'); return false;">The Collections</a>
                    <a href="http://halsteddesign.com/contact-us">Contact Us</a>
                    <a href="http://halsteddesign.com/newsletter">Newsletter</a>        
                </div>
            </div>
        </div>
    <div>
</body>
</html>

4 个答案:

答案 0 :(得分:0)

我个人认为最好使用:hover CSS属性作为菜单。它实现起来要容易得多,但您可能在移动设备上遇到问题。 https://developer.mozilla.org/fr/docs/Web/CSS/:hover

但是,如果您真的想在onc​​lick事件中使用它,则需要添加或绑定您的事件。以下是jQuery文档:http://api.jquery.com/bind/

一旦你绑定了这个事件,就必须使用你的函数的“event”参数来获取你点击的元素,然后显示正确的菜单。

答案 1 :(得分:0)

问题:

  1. 您无法处理要在功能中更改的元素。这是因为您使用的是getElementById(),但集合div没有定义id属性。

  2. 您正在引用要以不一致的方式切换显示的元素。有时您使用的是document.getElementById(shID+"-show"),有时您只是使用document.getElementById(shID)

  3. if语句中存在逻辑错误; if (document.getElementById(shID+'-show').style.display != 'none')中的条件应检查样式是否设置为none,如果是,我们要将样式更改为阻止,反之亦然。

  4. 解决方案

    1. 将一个id属性添加到集合div中,如下所示:

      <div id = "collections" class = "collections">
      
    2. 在showID函数中,将document.getElementById(shID+"-show")的所有实例替换为document.getElementById(shID)。事实上,更简洁的方法是只调用一次函数并将结果赋值给变量。

    3. 更改第二个if语句中的条件,以检查显示是否等于none。

    4. 提到所有更改后,您的最终功能将如下所示:

      function showHide(shID) {
          var el = document.getElementById(shID);
          if (el) {
              if (el.style.display === 'none' || el.style.display =='') {
                  el.style.display = 'block';
              }
              else {
                  el.style.display = 'none';
              }
          }
      }
      

      您可能会注意到我在if语句中添加了一个或。这是因为出于某种原因el.style.display的初始值(在函数中使用javascript设置之前)是&#39;&#39;。如果没有这个或条件,第一次显示菜单需要两次点击。

答案 2 :(得分:0)

非常简单的一行代码来执行show hide。只需几行即可设置。

此代码已经过测试并且运行良好。这仅适用于一个菜单,但可以轻松扩展到多个。
查看我的其他多个菜单的答案(在此之后添加)

设置代码在页面加载时运行一次。

设置:

创建一个数组来进行切换。这消除了if else。

var toggle = new Array;
toggle['none'] = 'block';
toggle['block'] = 'none';

将“集合div”读入变量。阅读一次,不再重复。

var div = document.getElementById('d1');

初始化div,以便DOM保持display:none。否则,第一次读取将为空。

div.style.display='none';

然后是showHide函数

function showHide(id) {div.style.display=toggle[div.style.display];}

切换数组toggle[div.style.display]中的div.style.display将为blocknone。其中,切换将返回相反的情况。同样如toggle['block']返回'none'并将其分配给集合div。

注意:

JS代码应位于结束正文标记</body>之前。这样,在HTML全部加载之前,它不会被解析。

使用有效的DOC类型也非常重要。如果不是浏览器必须猜测,可能猜错了。减慢自己的页面加载时间。

<!DOCTYPE html>
<html lang="en">

JavaScript代码:

</div><div>
<script language="javascript" type="text/javascript">//<![CDATA[
function showHide(id) {div.style.display=toggle[div.style.display];}
var toggle = new Array;
toggle['none'] = 'block';
toggle['block'] = 'none';
var div = document.getElementById('d1');
div.style.display='none';
//]]>
</script></body></html>

也是太多的白色空间。这可能会显着增加您的传输时间。大多数应该被压缩,因为你的页面应该被压缩。

 <!DOCTYPE html>
<html lang="en"><head><title>Menu Test</title><meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
html {overflow-y: scroll;margin: 0;  : 0;font-family: sans-serif;}
body {background-color: #fff;color: #444;margin: 0px;  : 0px;}
/* Begin top bar *************************/
#top-bar {-webkit-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);-moz-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);font-family: GillSansMTStd-Book;}
#top-bar-content {position: relative;height: 94px;margin: 0 auto;width: 1025px;text-align: "right";}
#top-bar .wrap {  -left: 33px;  -right: 33px;}
#top-bar .links {float: right;line-height: 94px;}
#top-bar a {outline:0;  }
#top-bar .links a {display: inline-block;color: #b9afa3;font-size: 14px;font-weight: normal;letter-spacing: .8px;text-decoration: none;margin-left: 30px;text-transform: uppercase;}
#top-bar .links a:hover,#top-bar .links a.active {color: #746758;background: url(/HalstedDesigns/catalog/view/theme/margaretha/image/nav-rule.gif) top center no-repeat;}
#top-bar .collections {display: none;background-color: #695d4f;color: #fff;position: absolute;top: 94px;width: 340px;text-align: center;margin-left: 80px;  -top: 10px;-webkit-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);-moz-box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);box-shadow: 0px 3px 5px rgba(100, 100, 100, 0.99);z-index: 5;}
#top-bar .collections a{  color:#fff;  display:block;  line-height:26px;    :10px 20px;  margin:0;  background-image:none;  text-transform:capitalize;  font-size:16px;}
#top-bar .collections a.the-ardmore-collection {  font-size:14px;}
#top-bar .collections a:hover,#top-bar .collections a.active {  background-color:#fff;  color:#695d4f;  background-image:none;}
</style></head><body>
<div id="top-bar">
 <div id="top-bar-content"><div class="wrap">
  <a href="/" title="Home" float="left"><img src="image/halsted-logo.png"; alt="Halsted Logo"></a>
  <div class="links">
   <div id="d1"class="collections">
    <a href="http://halsteddesign.com/the-ardmore-collection/" class="the-ardmore-collection font-gillsans ">THE ARDMORE COLLECTION</a>        
    <a href="http://halsteddesign.com/the-ardmore-collection/qalakabusha-sofa" class="lusitanaregular">Qalakabusha Sofa</a>    
    <a href="http://halsteddesign.com/the-ardmore-collection/qalakabusha-fabric-collection" class="lusitanaregular">Qalakabusha Fabric Collection</a>    
    <a href="http://halsteddesign.com/the-ardmore-collection/hand-bags" class="lusitanaregular">Hand bags</a>      
    <a href="http://halsteddesign.com/the-ardmore-collection/scatter-cushions" class="lusitanaregular">Scatter Cushions</a>     
    <a href="http://halsteddesign.com/the-ardmore-collection/batonka-stools" class="lusitanaregular">Batonka Stools</a>       
    <a href="http://halsteddesign.com/the-ardmore-collection/tablecloths" class="lusitanaregular">Tablecloths</a>     
    <a href="http://halsteddesign.com/the-ardmore-collection/place-mats" class="lusitanaregular">Place Mats</a>     
    <a href="http://halsteddesign.com/the-ardmore-collection/napkins" class="lusitanaregular">Napkins</a>     
    <a href="http://halsteddesign.com/the-ardmore-collection/table-runners" class="lusitanaregular">Table Runners</a>
   </div>        
    <a href="http://halsteddesign.com">Art Into Design</a>    
    <a href="#"  onclick="showHide(1);">The Collections</a>
    <a href="http://halsteddesign.com/contact-us">Contact Us</a>
    <a href="http://halsteddesign.com/newsletter">Newsletter</a>    
  </div>
 </div>
</div><div>
<script language="javascript" type="text/javascript">//<![CDATA[
function showHide(id) {div.style.display=toggle[div.style.display];}
var toggle = new Array;
toggle['none'] = 'block';
toggle['block'] = 'none';
var div = document.getElementById('d1');
div.style.display='none';
//]]>
</script></body></html>

注意: CDATA是将JS与HTML隔离开来。如果没有CDATA,JS在运行W3C HTML标记验证器时有时会导致HTML错误。这是推荐的最佳实践。
CDATA告诉浏览器它不是HTML。格式为

<![CDATA[  data goes here ]]>

它有两个斜杠的原因是注释掉JS解析器中的CDATA标记,但仍然被HTML解析器识别。

答案 3 :(得分:0)

多菜单解决方案:

多个菜单将showHide从一个扩展为两行代码。

注意:基础知识记录在此帖之前发布的另一篇答案中。

这次与前一种方法相比,我们将div保存为变量数组。重要的是,这个数组是在任何函数之外全局定义的。

此代码经过测试且运行良好。

初始化代码:

创建阵列

var toggle = new Array;
toggle['none'] = 'block';
toggle['block'] = 'none';
var div = new Array;

现在在init函数中初始化。不是必需的,但更可靠。这样它在页面加载之前就永远不会执行。

window.onload = init;

init首次获得showHide div。

然后将它们全部隐藏起来。

function init(){
  div[1] = document.getElementById('d1');
  div[2] = document.getElementById('d2');
  div[3] = document.getElementById('d3');
  div[4] = document.getElementById('d4');

  hideAll();
}

我添加了隐藏所有功能。当显示另一个菜单时,隐藏所有菜单会更容易,更快捷。您不希望同时打开两个菜单。您可以跟踪打开的菜单并特别关闭该菜单,但为什么要这么麻烦?

function hideAll(){
div[1].style.display='none';
div[2].style.display='none';
div[3].style.display='none';
div[4].style.display='none';
}

将其包装起来:

为了测试和演示目的,我修改了一些HTML。

HTML

    <a href="#" onclick="showHide(2)">Art Into Design</a>    
    <a href="#"  onclick="showHide(1)">The Collections</a>
    <a href="#" onclick="showHide(3)">Contact Us</a>
    <a href="#" onclick="showHide(4)">Newsletter</a> 
   <div id="d2"class="collections" >
    <a href="#" class="the-ardmore-collection font-gillsans ">THE ARDMORE COLLECTION</a>        
    <a href="" class="lusitanaregular">Qalakabusha Sofa</a>    
    <a href="" class="lusitanaregular">Qalakabusha Fabric Collection</a>    
   </div>
   <div id="d3"class="collections">
    <a href="">Hand bags</a>      
    <a href="">Scatter Cushions</a>     
    <a href="">Batonka Stools</a>       
   </div>
   <div id="d4"class="collections">
    <a href="">Tablecloths</a>     
    <a href="">Place Mats</a>     
    <a href="">Napkins</a>     
    <a href="">Table Runners</a>
    </div>
   </div>
    </div>
</div><div>

的JavaScript

<script language="javascript" type="text/javascript">
function showHide(id) {
  hideAll();
  div[id].style.display=toggle[div[id].style.display];
}
var toggle = new Array;
toggle['none'] = 'block';
toggle['block'] = 'none';
var div = new Array;
function hideAll(){
div[1].style.display='none';
div[2].style.display='none';
div[3].style.display='none';
div[4].style.display='none';
}
function init(){
div[1] = document.getElementById('d1');
div[2] = document.getElementById('d2');
div[3] = document.getElementById('d3');
div[4] = document.getElementById('d4');
hideAll();
}
window.onload = init;
</script></body></html>