触发内部类同时激活容器类作为'这个

时间:2017-01-30 09:54:33

标签: javascript jquery css class this

在我目前的示例中,您会看到'。崩溃'当有人点击div本身的任何地方时触发的容器。有许多' 崩溃' divs 但是每个人都是单独触发的,因为这个'在JS中。问题是我不希望整个容器成为触发器。

如何更换' .collapse'在JS中使用h2:取而代之但仍然触发.collapse为'这个'

让我知道这是否令人困惑所以我可以编辑我的问题以使其更容易理解。

HTML

<div class="collapse">
<h2>sometext
::after
</h2>
</div>

JS

$('.collapse').on('click',function(e){
  e.preventDefault();
  $(this).toggleClass('active');
});

http://codepen.io/mariomez/pen/jyaWax

1 个答案:

答案 0 :(得分:1)

我在代码中看不到任何h6,但您可以使用h2并使用$(this)parent()来选择它的父母。我希望这是你正在寻找的东西:

&#13;
&#13;
$('h2').on('click', function(e) {
  $(this).parent().toggleClass('active');
});
&#13;
@import url(http://fonts.googleapis.com/css?family=Roboto);
 html {
  height: 100%
}
body {
  font-family: 'Roboto', sans-serif;
  font-size: 15px;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none; background:url(https://unsplash.imgix.net/40/OTwgwURiQN6DLk8zIr8E_DSC00953.jpg?q=75&w=1080&h=1080&fit=max&fm=jpg&auto=format&s=408af6f15369c9d232097a79ff997fa7) center no-repeat;
  background-size: cover
}
h1 {
  color: #fff;
  text-align: center
}
.wrap {
  width: 80%;
  margin: 0 auto;
}
.collapse {
  background-color: rgba(255, 255, 255, 0);
  border-bottom: 1px solid #eee;
  cursor: pointer;
  color: #fff;
  padding: 10px;
  margin: 0px;
  max-height: 40px;
  overflow: hidden;
  transition: all 0.4s;
}
.collapse * {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.collapse.active {
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2);
  z-index: 200;
  color: #444;
  max-height: 3000px;
  padding: 10px 20px;
  margin: 10px -10px;
  transition: all 0.2s, max-height 4.8s;
}
.collapse h2 {
  font-size: 18px;
  line-height: 20px;
  position: relative
}
.transparent {
  background-color: rgba(255, 255, 255, 0) !important;
  color: #fff !important;
  box-shadow: none !important;
  margin: 0px !important;
  padding: 10px !important
}
.collapse h2::after {
  content: "+";
  text-align: center;
  position: absolute;
  width: 15px;
  height: 15px;
  border: 1px solid #ccc;
  border-radius: 50%;
  font-size: 12px;
  line-height: 15px;
  opacity: 0.5;
  right: 0;
  top: 0;
}
.collapse:hover h2::after {
  opacity: 1
}
.collapse.active h2::after {
  content: "-";
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <h1>Collapsible drawers</h1>

  <div class="collapse transparent">
    <h2>I am transparent</h2>
    The brain is like a muscle. When it is in use we feel very good. Understanding is joyous.
    <b>Carl Sagan</b> 
    <p>This one keeps the transparency</p>
  </div>
</div>
&#13;
&#13;
&#13;