1

これは、FacebookやGoogleの通知ボタンに似ており、ボタンをクリックしてウィンドウをポップアップし、そのボタンをもう一度クリックするか、通知divの一部ではない部分をクリックすると閉じます。

私の問題は、オブジェクトのクリックを解除したり、オブジェクトをクリックしたりするためのイベントが見つからないことです。

これは私が今持っているもので、ボタンをもう一度クリックした場合にのみポップアップするものを閉じることができます。

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

これは私が試したものですが、どちらのイベントも発生しません。

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

通知カウンターはh3です

画像パネルは画像です

4

2 に答える 2

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');
    }
});
于 2012-04-03T19:43:22.643 に答える
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()まで伝播するのを停止するために使用することもできます:http: //api.jquery.com/event.stopPropagation/document

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

クリックイベントハンドラー#my-element-idをトリガーする以外の要素をクリックするだけです。document

これ.on()はjQuery1.7の時点で新しく、この場合.bind()、古いバージョンを使用している場合は次のように置き換えることができます:http: //api.jquery.com/on

于 2012-04-03T19:41:45.940 に答える