在下面的代码片段中,当您单击en“open”按钮时,菜单成功打开,当您单击菜单外部时,菜单成功关闭。但是,如果我单击另一行的“open”按钮,而前一行的菜单仍然打开,则无法完全关闭菜单。
我遇到的问题是,e.stopPropagation()
方法阻止了点击冒泡来触发文档onclick
事件,该事件负责关闭菜单。然而,我也不能删除e.stopPropagation()
,因为它会导致这行document.documentElement.addEventListener("click", handle_click_outside_menu);
立即触发,从而导致菜单根本无法打开。
此外,我刚刚注意到,菜单是不关闭时,点击“关闭”按钮也:(
const menu = document.getElementById("menu");
const table = document.getElementById("table");
const option_buttons = Array.from(table.querySelectorAll("button"));
let target_row = null;
table.addEventListener("click", (e) => {
if (option_buttons.includes(e.target)) {
e.stopPropagation();
menu.style.top = e.target.getBoundingClientRect().top + "px";
menu.style.display = "flex";
menu.is_open = true;
target_row = e.target.closest(".row");
target_row.classList.add("selected");
document.documentElement.addEventListener("click", handle_click_outside_menu);
}
});
function handle_click_outside_menu(e) {
if (e.target !== menu && !menu.contains(e.target)) {
close_menu();
document.documentElement.removeEventListener("click", handle_click_outside_menu);
}
}
function close_menu() {
menu.style.display = "none";
menu.is_open = false;
target_row.classList.remove("selected");
target_row = null;
}
.table {
overflow: hidden;
}
.row {
display: flex;
gap: 2rem;
padding: 0.5rem 0;
border-bottom: 0.0625rem solid #ccc;
}
.row .btn_option > span {
pointer-events: none;
display: block;
}
.row:not(.selected) .btn_option > span:last-child {
display: none;
}
.row:is(.selected) .btn_option > span:first-child {
display: none;
}
.menu {
display: none;
position: absolute;
left: 10rem;
padding: 0.5rem;
background: #ccc;
flex-direction: column;
gap: 0.5rem;
}
.menu::before {
content: '';
position: absolute;
top: 0;
left: -0.75rem;
width: 0;
height: 0;
border-top: 0.75rem solid transparent;
border-bottom: 0.75rem solid transparent;
border-right: 0.75rem solid #ccc;
}
<div class="table" id="table">
<div class="row">
<span>Item 1</span>
<button class="btn_option" type="button"><span>Open</span><span>Close</span></button>
</div>
<div class="row">
<span>Item 2</span>
<button class="btn_option" type="button"><span>Open</span><span>Close</span></button>
</div>
<div class="row">
<span>Item 3</span>
<button class="btn_option" type="button"><span>Open</span><span>Close</span></button>
</div>
<div class="row">
<span>Item 4</span>
<button class="btn_option" type="button"><span>Open</span><span>Close</span></button>
</div>
<div class="row">
<span>Item 5</span>
<button class="btn_option" type="button"><span>Open</span><span>Close</span></button>
</div>
</div>
<div class="menu" id="menu">
<button type="button">View</button>
<button type="button">Edit</button>
<button type="button">Delete</button>
</div>
1条答案
按热度按时间db2dz4w81#
在你的脚本中有很多(imho不必要的)复杂性。例如,没有必要每次都添加/删除事件处理。如果你在处理函数中指定了 * 确切的触发器 *,
stopPropagation
就不需要了。我尝试简化代码:它在文档级别使用一个(单击)处理函数,并使用精确的规范来处理事件。按钮内容现在依赖于其父行的类。当父行未被选中时,处理函数打开菜单。否则,菜单关闭,该行被取消选择。