2017-10-20 88 views
1

這裏關閉下拉列表是我的代碼:https://jsfiddle.net/qesr0ybf/當其他下拉打開

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */ 
function myFunction() { 
    document.getElementById("myDropdown").classList.toggle("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'); 
     } 
    } 
    } 
} 

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */ 
function myFunction2() { 
    document.getElementById("myDropdown2").classList.toggle("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'); 
     } 
    } 
    } 
} 

當一個下拉列表是開放的,其他的都可以在同一時間打開。我試圖讓另一個關閉,一次只打開一個。如何做呢?

回答

0

更新你的函數是:

function myFunction() { 
    var d2 = document.getElementById("myDropdown2").classList; 
    if(d2.contains("show")) d2.toggle("show"); 
    document.getElementById("myDropdown").classList.toggle("show"); 
} 

和其它功能類似。

即,檢查另一個下拉列表是否包含show類,然後將其刪除。

更好的方法是跟蹤上次打開的下拉列表並關閉它,然後再打開另一個下拉列表,因爲您只需兩次下拉列表就可以了。

現場演示here

+0

工作很完美,謝謝! –

相關問題