更改div的类onclick并在单击按钮时删除类

时间:2016-09-28 18:22:57

标签: jquery

我想,如果我点击“btn”,“外部”和“btn”上添加的类将被删除,之前的类将被添加。我已经尝试过removeClass,但它确实有效吗?我该怎么做?我是jQuery的新手。还要忽略代码段中的错误。我没有把它们放在我的网站上。

$(document).ready(function(){
    $( "#outer" ).click(function() {
       $( "#outer" ).addClass( "block01_big" );
       $( "#btn" ).addClass( "button_visible" );
    });
       
   <!-- edited -->       
   $( "#btn" ).click(function() {
     $( "#outer" ).removeClass( "block01_big" );
     $( "#btn" ).removeClass( "button_visible" );
     <!-- i also tried -->
     $( "#outer" ).addClass( "block01" );
     $( "#btn" ).addClass( "button_invisible" );
   });
});
.container {
    min-height: 100vh;
    width: 99vw;
    background-color: red;
    
    overflow: hidden;
  }

.block01 { <!-- Normal Class for outer -->
    float: left;
    height: 500px;
    width: 33.33333%;
    background-color: green;
    position: relative; 
    
    transition: all 0.8s ease-in-out;
    -webkit-transition: all 0.8s ease-in-out;
    -o-transition: all 0.8s ease-in-out;
    -moz-transition: all 0.8s ease-in-out;
  }

.block01_big { <!-- outer gets bigger, by jQuery -->
   position: absolute;
   z-index: 999;
   width: 100%;
   height: 100%;
  }

.button_invisible { <!-- Not visible to the user -->
    height: 0px;
    width: 0px;
    border: none;
    
    transition: all 1s ease-in-out;
    -webkit-transition: all 1s ease-in-out;
    -o-transition: all 1s ease-in-out;
    -moz-transition: all 1s ease-in-out;
    
    position: absolute;
    right: 0;
    bottom: 0;
  }

.button_visible { <!-- Button gets visible, by jQuery -->
    margin-right: 75px;
    margin-bottom: 75px;
    
    height: 75px;
    width: 200px;
    border: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="block01" id="outer"> <!-- jQuery: onClick, change outer class to .block01_big & bt" to button_visible -->
    <button class="button_invisible" id="btn">Back</button> <!-- jQuery: onClick, change outer class to .block01 & btn to button_invisible (doesnt work)-->
  </div>
</div>


<!-- If I click first on the outer, the classes from outer and btn should change. Now my Problem: How can I do it, if I click the button, that the added classes from outer and btn gets removed? -->

1 个答案:

答案 0 :(得分:0)

嗯,不知何故切换不起作用。但现在确实如此。解决了。对于有同样问题的人:只需使用toggleClass代替addClass

(感谢Barmar,他已经提到过了)