2016-11-22 67 views
0

我得到一個菜單,顯示用戶何時單擊「按鈕」,所以我得到了下面的代碼。它在用戶點擊div時有效,但是當點擊span中的圖標時不起作用,任何人都可以解釋爲什麼?我嘗試了幾種組合,但似乎無法使其正常工作。點擊圖標時,onclick div與圖標不起作用

<style> 
.dropbtn { 
    z-index:4000; 
    background-color: #888677; 
    color: white; 
    padding: 10px 30px 10px 30px; 
    font-size: 22px; 
    color:#d6d1bd; 
    width:100px; 
    text-align:center; 
    display: table; 
    margin: 0 auto 
    } 
</style> 
<script> 
function getMenu() { 
    document.getElementById("myDropdown").classList.toggle("show"); 
} 
window.onclick = function(event) { 
    if (!event.target.matches('.dropbtn')) { 
     var dropdowns = document.getElementsByClassName("dropdown-content"); 
     var i; 
     for (i = 0; i < dropdowns.length; i++) { 
      var openDropdown = dropdowns[i]; 
      if (openDropdown.classList.contains('show')) { 
       openDropdown.classList.remove('show'); 
      } 
     } 
    } 
} 
</script> 

<div id="myDropdown"> 
my menu 
</div> 

<div style="border:0px;z-index:1000;" class="dropbtn" onclick="getMenu()" > 
<a onclick="getMenu()"> 
<span class="fa fa-bars">test</span> 
</a> 
</div> 
+0

你能否也請提供getMenu()函數的代碼?你真的不應該使用onclick事件... – junkfoodjunkie

+0

如果你可以創建一個jsfiddle,那將會很棒。圖標在哪裏? –

+0

爲什麼有兩次onclick? – epascarello

回答

0

在沒有看到使用getMenu()函數很難說。看起來很奇怪,你在div和anchor上都有onclick。如果的onclick從格觸發,那麼你不應該需要在所有我還以爲

如果我這樣做我自己,我可能會嘗試這樣的錨:

HTML:

<ul> 
    <li> 
    <span id="menu_button_1" class="menu_button"> 
     <i class="fa fa-bars" aria-hidden="true"></i> Menu 
    </span> 
    <ul class="sub_menu" id="sub_menu1"> 
     <li class="sub_menu_item"> 
     <i class="fa fa-square" aria-hidden="true"></i> Item 
     </li> 
    </ul> 
    </li> 
</ul> 

JS:

$(document).ready(function(){ 
    $('#menu_button_1').click(function(){ 
    $('#sub_menu1').toggle('fast'); 
    }); 
}); 

https://jsfiddle.net/trr0qnhp/1/

ħ這有助於。

+0

中的菜單示例,謝謝,是的,當我添加了JavaScript而不是完美的工作。改變了一點,所以它再次關閉。 https://jsfiddle.net/g86zy99y/ –

0

什麼,你可以嘗試是將字體 - 真棒字形圖標添加到使用CSS pseudo-elements在其中您可以將escape/variable代表您在set圖標你的錨,這由Font-Awesome提供。

在你的情況下,代碼看起來像這個東西simmilar:

a { 
    position: relative; /* Keeping the glyph-icon within the anchor */ 
}  

/* Pseudo element usage can be annotated with both : or :: (css2/css3 syntax) */ 
a::after { 
    /* We need to add the font itself so our CSS can know where the icons are */ 
    font-family: ' Font Awesome font '; 

    /* in this case, the content property is the actual icon we want to use */ 
    content: ' your escape/variable '; 

    /* We get our icon out of the document flow, e.g. its positioning inside the anchor */ 
    position: absolute; 

    /* additional styles for icon positioning */ 
}