我想在用户单击按钮时打开边栏。在打开侧边栏div之后,我希望在侧边栏外部单击时将其关闭。
侧边栏ID是根据用户ID动态生成的。我已经编写了代码,但无法正常工作。
function show_right_sidenav(element_id) {
var right_sidenav = document.getElementsByClassName("product-session-details");
for (var index = 0; index < right_sidenav.length; index++) {
right_sidenav[index].style.display = "none";
}
document.getElementById("accordionSidebar-" + element_id).style.display = "block";
current_open_sidenavbarid="accordionSidebar-" + element_id;
}
function hide_right_sidenav_by_id(element_id){
document.getElementById("accordionSidebar-" + element_id).style.display = "none";
}
window.addEventListener('click', function(e){
if (document.getElementById(current_open_sidenavbarid).contains(e.target)){
//click on sidebar
}else{
//click outside sidebar
element_id=current_open_sidenavbarid.split('accordionSidebar-')[1];
hide_right_sidenav_by_id(element_id);
}
});
此代码的问题在于,侧栏从不打开,而始终保持关闭状态。我在StackOverflow上尝试了其他答案,但无法弄清楚。