slideToggle on child with toggleClass on parent parent同时工作

时间:2017-08-19 16:14:31

标签: javascript jquery css

我试图向下滑动组件的内容,同时也改变同一组件顶部的一些样式。我找到了一种方法来做幻灯片然后改变课程,但我需要两个同时发生或者过渡看起来很笨重。这是我的代码 -

HTML

<div class="collapsable">
  <div class="top">
    <h1>Top Bar</h1>
  </div>
  <div class="content">
    <h2>Dropdown Content</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   </p>
 </div>
</div>
<p>content below component</p>

CSS(SCSS)

.collapsable {
  max-width: 500px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-bottom: 20px;
  .top {
    padding: 10px;
    border-bottom: 1px solid #ddd;
    background: #eee;
    transition: border-radius .3s ease;
    h1 {
      margin: 0px;
    }
  }
  .content {
    padding: 10px;
    display: block;
    overflow: hidden;
    h2 {
      margin: 0px;
      margin-bottom: 10px;
    }
    p {
      margin: 0px;
    }
  }

  &.up {
    .top {
      border-bottom: 0px;
      border-radius: 5px;
    }
    .content {
      display: none;
    }
  }
}

的Javascript

$(document).ready(function() {
  $('.top').click(function() {
    var $this = $(this);
    var content = $this.siblings($('.content'));
    var component = $this.closest($('.collapsable'));

    content.slideToggle(function() {
      component.toggleClass('up');
    });

  });
});

这是一个codepen - https://codepen.io/Davez01d/pen/VzQOgq

2 个答案:

答案 0 :(得分:0)

以下更新的代码。

$(document).ready(function() {
  $('.top').click(function() {
    var $this = $(this);
    var content = $this.siblings($('.content'));
    var component = $this.closest($('.collapsable'));

    $('.content:nth-of-type(1)').slideToggle(function() {
      component.toggleClass('up');


    });
    $('.content:nth-of-type(2)').slideToggle();
    /*component.toggleClass('up');
    content.slideToggle();*/

  });
});

答案 1 :(得分:0)

这是什么,你需要一个简单的改变

$(document).ready(function() {
  $('.top').click(function() {
    var $this = $(this);
    var content = $('.content');
    var component = $this.closest($('.collapsable'));

    content.slideToggle(function() {
      component.toggleClass('up');
    });
    
    /*component.toggleClass('up');
    content.slideToggle();*/
    
  });
});