簡體   English   中英

jQuery-DOM元素集中時隱藏下拉菜單

[英]jQuery - hide dropdown when DOM element is focused

我必須顯示一個下拉菜單,現在我想隱藏DOM中的另一個元素(不是下拉菜單或下拉菜單的子級)時的隱藏菜單。

(當元素!== dropdown || dropdown的子元素集中在DOM中時,隱藏dropdpown)

focusout()沒有結果:

$('a').on('click',function(){
        $('.drop.user-menu').fadeIn(); 
});

$('.drop.user-menu').on('focusout',function(){
        $(this).fadeOut();
        alert('antani');
});

任何想法?

jsfiddle這里: 示例

event.target()在這種情況下將很有用:

$('.drop.user-menu').on('focusout',function(e){
    if(e.target !== this){
      $(this).fadeOut();
      alert('antani');
    }
});

更新:

檢查一下,看看是否有幫助:

 $('.a').on('click', function (e) {
     e.stopPropagation();
     $('.drop.user-menu').fadeToggle();
 });
 $('.drop.user-menu').on('click', function (e) {
     e.stopPropagation();
     $('.drop.user-menu').fadeIn();
 });
 $(document).on('click', function (e) {
    if (e.target !== $('.drop.user-menu') && e.target !== $('.a')) {
       $('.drop.user-menu').fadeOut();
    }
 });

上面的腳本在此提琴中單擊完成

沒有觸發focusfocusout事件,因為您未對表單字段進行操作。

這可能就是您想要的: 如何檢測元素外部的單擊?

var menu = $('.drop.user-menu');
menu.on('click',function(e){
    e.stopPropagation();  // stop clicks on menu from bubbling to document
});
$('a').on('click', function (e) {
    menu.fadeIn();
    e.stopPropagation(); // stop clicks on <a> from bubbling to document
});
$(document).on('click',function(e){
    // any other click
    if (menu.is(":visible")) {
        menu.fadeOut();
    }
});

http://jsfiddle.net/BBxEN/10/


更新

正如Derek指出的那樣,這對鍵盤用戶不是很友好。 考慮為用戶提供一種使用鍵盤快捷鍵打開和關閉菜單的方式。

DIV不能取得或失去焦點(除非它具有tabindex )。 您必須給它一個tabindex或在div.drop.user-menu添加一個可聚焦的元素。 請參閱哪些HTML元素可以獲得焦點?

然后,您還必須顯式地賦予該元素(或其中的一個元素)焦點(使用.focus() ),因為簡單地淡入它並不會使其獲得焦點。

當元素模糊時,請檢查新的活動元素是否仍在菜單中。 如果不是,請淡出菜單。

請參閱工作示例

您可以模糊處理,這是您想要的嗎?
嘗試這個:

$('.drop.user-menu').on('blur',function(){
   $(this).fadeOut();
   alert('antani');
});

暫無
暫無

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

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