首页 文章

单击body时隐藏div并在单击按钮时显示div

提问于
浏览
0

我已经在一个按钮上应用了点击事件并显示了一个div . 我也在身体标签上应用了onclick事件来隐藏div.But当我点击也在体内的按钮然后点击按钮调用和div显示的功能 . 同时onclick身体呼叫事件和div隐藏 .

我想在点击按钮时显示div并在点击任何其他地方时隐藏它 .

任何人都可以帮助我提前谢谢

6 回答

  • 1
    $(function(){
        $("body").click(function(){
            $("#divID").hide();
        });
        $("#btnShow").click(function(event){
            $("#divID").show();
            event.stopPropagation();
        });
    })
    
  • 0

    你可以尝试下面的东西 -

    $('body.aClass').click(function(){
        $('#divId').hide(); 
        $(this).removeClass('aClass'); 
    });
    $('button').click(function(){ 
        $('#divId').show(); 
        $('body').addClass('aClass'); 
    });
    
  • 1

    使用event.stopPropagation()可防止事件冒泡DOM树,从而阻止任何父处理程序收到事件通知 .

    jQuery

    $('button').click(function(){
        alert('show');
        $('div').show();
        event.stopPropagation(); // <<<<<<<<
    });
    
    $('body').click(function(){
        $('div').hide();
        alert('hide');
    })
    

    见演示:http://jsfiddle.net/MX4xA/

  • 3

    只是一个简单的例子 . 未经测试 . 除非你提供更多信息,否则不能给予更多 .

    HTML:

    <body>
       <div id="element">Show / hide this</div>
       <div id="button">Click me!</div>
    </body>
    

    JS:

    $(document).ready(function() {
        // Click event on body hide the element
        $("body").click(function() {
            $("#element").hide("fast");
        });
    
        // Click event on button show the element
        $("#button").click(function() {
            $("#element").show("fast");
            event.stopPropagation();
        });
    }
    

    根据artwl的回答,您将需要使用event.stopPropagation()来防止事件冒泡DOM树 .

  • 0
    <script>
    $(document).ready(function(){
     $("body").click(function(){
            $("#effect").hide();
        });
    
      $("#button").click(function(){
        $("#effect").toggle();
        event.stopPropagation();
      });
    
    
    
       $( "#effect" ).hide();
    });
    </script>
    
  • 1

    在这里,我为上述问题做了完整的垃圾箱 .

    DEMO: http://codebins.com/bin/4ldqp9s

    每当你使用语句event.stopPropagation();在jquery函数中,你必须将事件变量定义为函数参数,然后它将被视为事件对象变量,并且它工作正常 .

    HTML:

    <div id="panel">
      <div id="box">
        Div To be Hide/Show
      </div>
      
    <input type="button" id="btn1" name="btn1" value="Show Div"/> </div>

    CSS:

    #box{
      height:50px;
      width:200px;
      background:#55a1dc;
      vertical-align:middle;
      text-align:center;
      border:1px solid #334499;
      display:none;
    }
    

    JQuery:

    $(document).ready(function() {
        // Click event on body hide the element
        $("body").click(function(event) {
            $("#box").hide(600);
            event.stopPropagation();
        });
    
        // Click event on button show the element
        $("#btn1").click(function(event) {
            $("#box").show(600);
            event.stopPropagation();
        });
    });
    

    DEMO: http://codebins.com/bin/4ldqp9s

相关问题