簡體   English   中英

顯示和隱藏下拉菜單的JavaScript函數

[英]Show and hide JavaScript function for drop-down menu

我正在嘗試為我正在工作的網站創建一個下拉菜單,但是在隱藏和顯示我一直在使用的代碼的下拉菜單時遇到問題。

基本上,我需要這樣:

<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>

我個人認為最好將:hover CSS屬性用於菜單。 它易於實現,但是在移動設備上可能會出現問題。 https://developer.mozilla.org/fr/docs/Web/CSS/:hover

但是,如果確實要在onclick事件上使用它,則需要添加或綁定事件。 這是它的jQuery文檔: http : //api.jquery.com/bind/

一旦綁定了事件,就必須使用函數的“事件”參數來獲取單擊的元素,然后顯示正確的菜單。

問題:

  1. 您對要在函數內部進行更改的元素沒有任何處理。 這是因為您使用的是getElementById() ,但是collection div沒有定義id屬性。

  2. 您正在引用要不一致地切換其顯示的元素。 有時您正在使用document.getElementById(shID+"-show") ,而有時您只是在使用document.getElementById(shID)

  3. 您的if語句中存在邏輯錯誤; if (document.getElementById(shID+'-show').style.display != 'none')應檢查樣式是否設置為none,如果是這樣,我們希望將樣式更改為block,反之亦然。

解決方案

  1. 像這樣向集合div添加一個id屬性:

     <div id = "collections" class = "collections"> 
  2. 在showID函數內部,將document.getElementById(shID+"-show")所有實例替換為document.getElementById(shID) 實際上,更干凈的方法是只調用一次函數並將結果分配給變量。

  3. 更改第二個if語句中的條件,以檢查顯示是否等於無。

提及所有更改后,最終功能將如下所示:

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設置之前)為。 如果沒有此條件,則第一次單擊將需要兩次單擊才能顯示菜單。

非常簡單的一行代碼即可執行以顯示隱藏。 只需設置幾行即可。

此代碼已經過測試並且運行良好。 這僅用於一個菜單,但可以輕松擴展為多個菜單。
請參閱我的其他答案以獲取多個菜單 (在此菜單之后添加)

頁面加載時,安裝代碼將運行一次。

設置:

創建一個數組進行切換。 這消除了if else。

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

將“ collects 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]可以是blocknone 無論哪種情況,切換都會返回相反的結果。 就像是toggle['block'] ,它返回'none' ,並將其分配給集合div。

注意:

JS代碼應位於結束body標簽</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,則在運行W3C HTML標記驗證器時,JS有時會導致HTML錯誤。 這是推薦的最佳實踐。
CDATA告訴瀏覽器它不是HTML。 格式為

<![CDATA[  data goes here ]]>

它有兩個斜杠的原因是從JS解析器中注釋掉了CDATA標記,但仍被HTML解析器識別。

多菜單解決方案:

多個菜單將showHide從一兩行代碼展開。

注意:基礎知識記錄在此帖子的另一答案中。

這次與以前的單個方法相比,我們將div保存到變量數組中。 在任何函數之外全局定義此數組很重要。

此代碼是經過測試的,效果很好。

初始化代碼:

創建數組

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

現在在init函數中進行初始化。 不需要,但更可靠。 這樣,它將永遠不會在頁面加載之前執行。

window.onload = 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM