Javascript 使用 document.onclick 关闭下拉菜单
Javascript closing a dropdown with document.onclick
我有一个使用 ul 和 li 的下拉菜单:
<img class="options_toggle" src="assets/down_arrow.png"onclick="toggle_display('options');"/>
<ul id="options" class="options_content hide">
<li>
option one
</li>
</ul>
options_toggle 函数在选项 ul 中的 "hide" 和 "show" class 之间来回交换。现在我只想在用户单击除选项切换之外的任何地方时隐藏它:
$(document).ready(function () {
document.onclick = function(e) {
// prevent the dropdown from closing instantly when you click the toggle to open it
$(".options_toggle").click(function (e) {
e.stopPropagation();
});
// hide the dropdown
$(".options_content").removeClass("show");
$(".options_content").addClass("hide");
};
});
但问题是,他们第一次加载页面时,必须先在某处单击一次,然后才能单击切换按钮。第一次点击后它工作正常,他们只需要首先点击两次,这可能很烦人。
知道它在做什么以及它为什么取消或忽略第一次切换吗?谢谢
在另一个事件处理程序中添加一个事件处理程序通常是错误的。只需在顶层绑定您的 $(".options_toggle").click()
处理程序。
$(document).ready(function() {
$(".options_toggle").click(function(e) {
// prevent the dropdown from closing instantly when you click the toggle to open it
e.stopPropagation();
});
$(document).click(function(e) {
// hide the dropdown
$(".options_content").removeClass("show");
$(".options_content").addClass("hide");
});
});
我有一个使用 ul 和 li 的下拉菜单:
<img class="options_toggle" src="assets/down_arrow.png"onclick="toggle_display('options');"/>
<ul id="options" class="options_content hide">
<li>
option one
</li>
</ul>
options_toggle 函数在选项 ul 中的 "hide" 和 "show" class 之间来回交换。现在我只想在用户单击除选项切换之外的任何地方时隐藏它:
$(document).ready(function () {
document.onclick = function(e) {
// prevent the dropdown from closing instantly when you click the toggle to open it
$(".options_toggle").click(function (e) {
e.stopPropagation();
});
// hide the dropdown
$(".options_content").removeClass("show");
$(".options_content").addClass("hide");
};
});
但问题是,他们第一次加载页面时,必须先在某处单击一次,然后才能单击切换按钮。第一次点击后它工作正常,他们只需要首先点击两次,这可能很烦人。
知道它在做什么以及它为什么取消或忽略第一次切换吗?谢谢
在另一个事件处理程序中添加一个事件处理程序通常是错误的。只需在顶层绑定您的 $(".options_toggle").click()
处理程序。
$(document).ready(function() {
$(".options_toggle").click(function(e) {
// prevent the dropdown from closing instantly when you click the toggle to open it
e.stopPropagation();
});
$(document).click(function(e) {
// hide the dropdown
$(".options_content").removeClass("show");
$(".options_content").addClass("hide");
});
});