2015-08-26 45 views
1

其次是HTML DOM:

<div class="opt"> 
    Options 
    <div class="panel"> 
     <h3>i am in panel!!</h3> 
    </div> 
</div> 

當我在.opt點擊它會顯示.panel內容,但後來我需要觸發另一個事件隱藏點擊.opt元素外部的.panel

的jQuery:

$('.opt').click(function(){ 
    var $this = $(this); 
    $this.find('.panel').fadeIn(); 
    $this.blur(function(){ 
     $this.find('.panel').fadeOut(); 
     alert('i am from blur'); 
    }); 
}); 

下面是一個演示JsFiddle

blur()法不執行,我在做什麼錯在這裏技術上?

+1

看http://stackoverflow.com/questions/1985292/problem-with-jquery-blur-event-on-div-element。我用一個tab索引屬性嘗試了你的代碼,它可以工作。 – jnoreiga

+1

看這樣的: [http://stackoverflow.com/questions/1985292/problem-with-jquery-blur-event-on-div-element][1] [1]: http://stackoverflow.com/questions/1985292/problem-with-jquery-blur-event-on-div-element – DZanella

+0

我注意到它適用於'mouseleave'而不是模糊,但是,它不聽點擊 – rakibtg

回答

2

這工作,如果你去定義tabIndex屬性爲DIV ... 嘗試:

HTML

<div class="opt" tabindex="3"> 
    Options 
    <div class="panel"> 
     <h3>i am in panel!!</h3> 
    </div> 
</div> 

JS

$('.opt').click(function(){ 

    $(this).find('.panel').fadeIn(); 
    $(this).blur(function(){ 
     $(this).find('.panel').fadeOut(); 
     alert('i am from blur'); 
    }); 
}); 
1

你可以淡出綁定然後添加:

event.stopPropagation(); 

您的選擇類點擊處理程序來實現此目的。

Here is an example on codepen

5

您可以嘗試在身體,而不是模糊的單擊事件。看看 https://jsfiddle.net/y0wsfpvb/7/

$('.opt').click(function(){ 
    var $this = $(this); 
    $this.find('.panel').fadeIn(); 
}); 


$('body').click(function (e){ 
    if($(e.target).closest(".opt").length > 0 == false) { 
     $('.panel').fadeOut(); 
     alert('fake blur'); 
    } 
}); 
+0

我不明白什麼,如果{...}做點擊身體時..可以請描述一下? – rakibtg

+0

如果目標是.opt,我不想關閉面板,所以我返回false來退出事件。 click事件在body上,但是如果inner元素在.opt中,我返回false來退出方法來保持面板打開。 –

+0

好吧,我認爲這會更好,而不是stopPropagation().opt ..你覺得怎麼樣? – rakibtg