2016-11-19 98 views
0

我有一個Javascript菜單。然而,懸停並點擊主菜單項可以正常工作,但無法使下拉框工作。無法獲得javascript下拉菜單

menu.js是

/* When the user clicks on the button, 
    toggle between hiding and showing the dropdown content */ 
function myFunction() { 
    //document.getElementById("myDropdown").classList.toggle("show"); 
    //document.getElementsByClassName("dropdown-content").show); 
    //document.getElementById("pmd").classList.toggle("show"); 
    pmd.show; 
} 
} 
// Close the dropdown if the user clicks outside of it 
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'); 
     } 
    } 
    } 
    if(!event.target.matches('.dropbtnpm')) { 
    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'); 
    } 
    } 
} 

我的,我想一個下拉如下所示菜單HTML。我只是試圖讓它與「測試」的文本一起工作。我可以做鏈接後

<td><button onmouseover="myFunction();" 
onclick="location.href='property-mngt.html';" value="Property Management" 
class="dropbtn">PROPERTY MANAGEMENT</button> 
<div id="pmd" class="dropdown-content"> test </div> 
</td> 

的CSS是

.dropbtn { 
    border: none; 
    padding: 16px; 
    cursor: pointer; 
    background-color: #ffffff; 
    color: black; 
    height: 125px; 
    min-height: 125px; 
    font-size: 12px; 
} 
.dropbtn:hover, .dropbtn:focus { 
    background-color: #004b8d; 
    color: white; 
    font-size: 12px; 
} 
.dropdown { 
    position: relative; 
    color: #ffff33; 
} 
.dropdown-content { 
    position: absolute; 
    background-color: #f9f9f9; 
    min-width: 160px; 
    display: none; 
} 
.dropdown-content a { 
    padding: 12px 16px; 
    text-decoration: none; 
    display: block; 
    color: white; 
} 
.dropdown a:hover { 
    background-color: #f1f1f1; 
    color: black; 
} 
.show { 
    border: 1px solid #33ccff; 
    display: block; 
    visibility: visible; 
    background-color: #004b8d; 
    color: white; 
    font-family: Arial,Helvetica,sans-serif; 
    font-size: small; 
} 
.dropdown-content a:hover { 
    background-color: #f1f1f1; 
    color: black; 
} 

我的目標是有懸停在那個特定的菜單項時的下拉列表中出現。如果我將html更改爲<div id="pmd" class="dropdown-content.show"> test </div>'test'顯示在菜單上。

我一直在獲取該菜單項的鼠標懸停來顯示下拉菜單。

+4

的JavaScript代碼似乎並不完整。 'pmd.show'應該做什麼,'pmd'是什麼,並且至少有一個花括號太多。 – gus27

+1

僅僅因爲我很好奇:爲什麼你使用javascript來顯示菜單?爲什麼不使用CSS和HTML,這樣就可以確保你的菜單對所有人都可用,甚至包含JS和CSS的人都可以關閉。 – junkfoodjunkie

+1

另外,你爲什麼使用'

回答

1

您試圖顯示多個元素。拿第一個和正確顯示它。

document.getElementsByClassName('dropdown-content')[0].style.display = 'block' 

或使用使用document.querySelector('dropdown-content')

+0

我用第二個選項,它工作。但是,根據上述評論,我將菜單改爲CSS/HTML。 –