2012-04-03 22 views
1

這與Facebook和Google通知按鈕類似,點擊它們並彈出一個窗口,如果您再次單擊該按鈕,或者如果您單擊任何不屬於通知區域的部分。Jquery切換UI元素的可見性,但如果沒有單擊div的任何部分,則使其不可見

我的問題是我找不到一個事件來解除一個對象或點擊它。

這就是我現在所擁有的,只有當你重新點擊按鈕時你才能關閉彈出的內容。

notifycounter.click(function() { 
    return imagepanel.toggle(); 
}); 

這是我嘗試過,但沒有事件觸發:

notifycounter.focusin(function() { 
    return imagepanel.toggle(); 
}); 
notifycounter.focusout(function() { 
    return imagepanel.hide(); 
}); 

通知計數器是H3

圖像面板是一個img

+2

爲什麼'return' ...? – elclanrs 2012-04-03 19:42:28

回答

2

試試這個。

notifycounter.click(function(e) { 
    imagepanel.toggle(); 
    e.stopPropagation();//this will stop the event bubbling 
}); 

$(document).click(function(){ 
    if(imagepanel.is(':visible')){ 
     imagepanel.hide(); 
    } 
}); 

您可以像這樣對其進行優化。

notifycounter.click(function(e) { 
    imagepanel.toggle(); 
    e.stopPropagation();//this will stop the event bubbling 

    if(imagepanel.is(':visible')){ 
     $(document).one('click.imagepanel', function(){ 
      imagepanel.hide(); 
     }); 
    } 
    else{ 
     $(document).unbind('click.imagepanel'); 
    } 
}); 
+0

將.hide()包裹在'if(imagepanel.is(':visible')){'可以幫助嗎? – 2012-04-03 19:49:19

+1

@ RokoC.Buljan - 是的,這很有道理。 – ShankarSangoli 2012-04-03 19:50:30

+0

不錯的一個人從我的 – 2012-04-03 19:51:43

1

您可以綁定到document元素並檢查事件的目標是否是正確的元素:

$(document).on('click', function (event) { 
    if (event.target == 'my-element-id') { 
     //the element was clicked-on 
    } else { 
     //something other than the element was clicked-on 
     $('#my-element-id').hide(); 
    } 
}); 

您還可以使用event.stopPropagation()從傳播到document元素停止事件:http://api.jquery.com/event.stopPropagation/

$('#my-element-id').on('click', function (event) { 
    event.stopPropagation(); 
}); 
$(document).on('click', function() { 
    $('#my-element-id').hide(); 
}); 

只有點擊比#my-element-id其他元素將觸發document click事件處理程序。

注意.on()是新的一樣的jQuery 1.7的,在這種情況下,如果您使用的是舊版本可以與.bind()更換:http://api.jquery.com/on

+0

感謝您的快速反應和很好的解釋。 – prashn64 2012-04-03 20:02:09