4

ボタンをクリックすると開くパネルを作ろうとしています。私はボタンを持っています、私はパネルを持っています。click()イベントで開きます。そのボタンをもう一度押すと、閉じます。

$('#button').click(function() {

    $('#panel').toggle();
});

ユーザーが#buttonまたは以外の場所をクリックすると#panel、それも閉じます。

PS私はこのようなことを試しましたが、それは望ましい動作ではありません.

$('#button').mouseenter(function() {

    $('#panel').show();

}).mouseleave(function() {

    setTimeout(function() {
        $('#panel').hide();
    }, 2000);
});
4

4 に答える 4

4
$(
    function(){
        $("#button").click( function(){ $("#panel").toggle(); } );
        $(document).click( function(e){
            var elm = jQuery(e.target);
            if(elm.is("#button") || elm.is("#panel") || elm.parents("#panel").length>0)return;
            $("#panel").hide();
        });
    }
);

[ e.target]がクリックされた要素ではないことを確認します。

  1. ボタンelm.is("#button")
  2. パネルelm.is("#panel")
  3. パネル内の任意の要素elm.parents("#panel").length>0
于 2011-07-19T15:43:54.893 に答える
3

これを試して

$('#button').click(function(e) {

    $('#panel').toggle();
    e.stopPropagation();

});

$('#panel').click(function(e) {

    e.stopPropagation();

});

$(document.body).click(function(e) {
    if($('#panel').is(":visible")){
      $('#panel').hide();
    }
});
于 2011-07-19T15:31:46.327 に答える
1

あなたの要求に対する直接的な答えは

$('body').click(function(e)

   var starter = $(e.target);
   if ( starter.is('#button, #panel') || starter.closest('#panel').length > 0 ) return;

   setTimeout(function() {
       $('#panel').hide();
   }, 2000);

})

しかし、マウスアウトで何をしようとしたかを見ると、これがより良いアプローチであると考えるかもしれません

$('#button').click(function() {

    $('#panel').show();

});

$('#panel').mousenter(function() {

    var closetimer = $(this).data('closetimer');  // retrieve the timer if it exists
    clearTimeout(closetimer); // and clear the timeout when we re-enter to cancel the closing

}).mouseleave(function() {

    var closetimer = setTimeout(function() {
        $('#panel').hide();
    }, 2000);

    $(this).data('closetimer', closetimer); // store the timer with the panel so we can cancel it if we need

});
于 2011-07-19T15:32:54.527 に答える
0

画面 (またはページ) の 100% を占める、パネルの後ろに非表示の要素を配置します。この要素には、両方のパネルを閉じるクリック イベントが与えられます。

これにより、クリックしてパネルを閉じても、サイトの残りの部分で他のアクションがトリガーされなくなります。

必要に応じて、レイヤー化された要素を灰色で半透明にすることもできます。これにより、パネルが表示されている間、サイトの残りの部分をゴースト化する効果が得られます. この効果は Javascript ポップアップ ボックス スクリプトで非常に頻繁に使用されます。フルスクリーン要素を既に配置しているため、事実上無料で実行できます。あなたはそれをスタイリングする必要があります。

于 2011-07-19T15:32:42.607 に答える