zoukankan      html  css  js  c++  java
  • jQuery 点击显示再次点击隐藏

    <html>
        <head>
            <script type="text/javascript" src="/jquery/jquery.js"></script>
        </head>
        <body>
            <div>
                <span class="color">深咖色</span>
                <div class="cc"></div>
            </div>
            <div>
                <span class="size">11*11</span>
                <div class="bb"></div>
            </div>
        </body>
    </html>
                
    1 .color,.size{  font-size:14px; color:black;}
    2 .cc{ width:300px;height:100px;background:red;}
    3 .bb{ width:300px;height:100px;background:red;}

    第一种是简单的显示和隐藏,使用了bind()和toggle();

    1 $(function(){
    2      $(".color").bind("click",function(){ $(this).next(".cc").toggle();});
    3      $(".size").bind("click",function(){ $(this).next(".bb").toggle();});
    4 });

    toggle()方法自己就有显示隐藏的作用。

    但是这段js的缺点是,当我点击“深咖色”显示红色方块,再次点击“11*11”时,绿色方块出现,但是红色方块也不会隐藏,如图:

    第二种方法:改进上述的缺点,当再次点击时,隐藏其他,只出现点击出现的相应内容。

    $(function(){
      $(".color").bind("click",function(){ $(this).next(".cc").show(); $(".bb").hide(); }); $(".size").bind("click",function(){ $(this).next(".bb").show(); $(".cc").hide(); }); });

    第三种,在第二种的基础上添加,当点击显示时,出现相应内容,点击其他消失,或者点击其他空白处消失。

      $(function(){
        
        $(".color").bind("click",function(){ 
          $(this).next(".cc").show();
          $(".bb").hide();
        });
           $(".size").bind("click",function(){ 
          $(this).next(".bb").show();
           $(".cc").hide();
       });
     
    $(".color").on("click", function(e){
        $(document).one("click", function(){
            $(".cc").hide();
          $(".bb").hide();
        });
    
        e.stopPropagation();
    });
    $(".cc").on("click", function(e){
        e.stopPropagation();
    });
    
    $(".size").on("click", function(e){
        $(document).one("click", function(){
            $(".bb").hide();
        $(".cc").hide();
        });
    
        e.stopPropagation();
    });
    $(".bb").on("click", function(e){
        e.stopPropagation();
    });
     });

     one() 方法为被选元素附加一个或多个事件处理程序,并规定当事件发生时运行的函数。

    当使用 one() 方法时,每个元素只能运行一次事件处理器函数。

  • 相关阅读:
    高并发系统如何设计
    PHP的垃圾回收机制(开启垃圾回收机制后的优缺点是什么)
    移动端网站如何开发(电脑端网站到手机端网站我们需要在html代码中添加哪个meta标签)
    家庭洗车APP --- Androidclient开展 之 网络框架包介绍(一)
    一天JavaScript示例-判定web页面的区域
    左右margin top问题百分比值
    Ubuntu14.04设备JDK
    三层架构,四大天王——删
    MEMO:UIButton 中的图片和标题 左对齐
    HDU 3874 离线段树
  • 原文地址:https://www.cnblogs.com/Jinmj/p/5239400.html
Copyright © 2011-2022 走看看