簡體   English   中英

如何檢測用戶何時觸摸菜單或其子女以外的其他內容?

[英]How can I detect when a user touches something other than a menu or it's children?

我正在嘗試編寫一些JavaScript來處理下拉菜單中的觸摸交互。 這很好用,除了當用戶點擊它時我無法弄清楚如何隱藏菜單。

我的腳本如下:

// mark all menu items as inative
function mark_all_inactive(elem) {
    elem.find(".is-active").removeClass("is-active");
    elem.find("[aria-hidden=false]").attr("aria-hidden", "true");
}

// mark element as active
function mark_active(elem) {
    elem.closest(".menu-list_item").addClass("is-active");
    elem.siblings("[aria-hidden]").attr("aria-hidden", "false");
}

// open on touchstart
jQuery(".menu-list_item").not(".menu-list_item.-mega .menu-list_item.-parent").on("touchstart", function(e) {
    if (!jQuery(this).hasClass("is-active") && jQuery(this).children("[aria-hidden]").length) {
        e.preventDefault();
        mark_all_inactive(jQuery(this).closest(".menu-list"));
        mark_active(jQuery(this).children(".menu-list_link"));
    }
});

// hide on focusout
jQuery(".menu-list").on("focusout", ".menu-list_link", function() {
    var parent_item = jQuery(this).closest(".menu-list_item.-parent.is-active");

    if (parent_item.length) {
        // timeout required for the next element to get focus
        setTimeout(function() {
            if (!parent_item.find(":focus").length) {
                parent_item.removeClass("is-active");
                parent_item.children("[aria-hidden]").attr("aria-hidden", "true");
                parent_item.closest(".menu-list_item.-parent.is-active").find(".menu-list_link").first().trigger("focusout");
            }
        }, 10);
    }
});

正如您所看到的,我正在使用touchstart添加一些類,它們完美無缺。 嘗試刪除這些類時會出現問題。

代碼的focusout位主要用於鍵盤導航,但我想調整它以便在您點擊菜單時觸發。

根據我的理解,移動瀏覽器通常不會在遠離某些東西時觸發focusout 這對我來說似乎很奇怪,因為你認為無論輸入類型如何,從某些東西中focusout都會引起focusout ,但這不是重點。

我已經看了一下touchend ,但是在抬起你的手指之后,它似乎立即開火,這不是我想要的。 目標是點擊一次添加類,然后能夠抬起手指選擇子鏈接(也可以包含彈出菜單,從而重新使用相同的touchstart腳本)。 然后,當您點擊不是活動菜單的任何地方時,請刪除這些類。

所以,關於這樣一個問題:是否可以修改腳本的focusout位置,以適應從菜單或它的孩子focusout 如果沒有,我將如何編寫第二個腳本來完成該任務?

您可以在以下網址查看實時演示:

https://framework.ghostlyco.de/

我想出來了,但我不知道這是最好的方式。 將事件附加到整個文檔似乎有點愚蠢,但這有效:

// hide on touch away
jQuery(document).on("touchstart", function(e) {
    if (!jQuery(e.target).closest(".menu-list_item.-parent.is-active").length) {
        jQuery(".menu-list_item.-parent.is-active").children("[aria-hidden]").attr("aria-hidden", "true");
        jQuery(".menu-list_item.-parent.is-active").removeClass("is-active");
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM