如何在点击时使用动画或其他东西轻轻改变div的大小

时间:2018-06-03 06:39:39

标签: javascript jquery css dropdown effect

我只想轻轻改变div的大小。 当我点击div时,我可以展开并折叠那些h5元素 但是我怎样才能调整这个动作的动画呢? 我已经尝试应用关键帧动画或css转换,但我失败了



for (var i = 1; i <= 5; i++) {
  $('#sampleNumberList').append('<h5>#' + i + '</h5>');
}
$('#topSampleNum').on('click', function() {
  if ($('#sampleNumberList').hasClass('active') === true) {
    $('#sampleNumberList').removeClass('active');
  } else {
    $('#sampleNumberList').addClass('active');
  }
});
&#13;
.topFloatBar {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 5;
  text-align: center;
  background-color: #e3e3e3;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

#sampleNumberList {
  max-height: 0;
  overflow: hidden;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="topFloatBar" id="topSampleNum">
  <h2 id="mainNumber"> #1 </h2>
  <div id="sampleNumberList"> </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

喜欢这个吗?

var sampleList = document.querySelector('#sampleNumberList');
var listTrigger = document.querySelector('#mainNumber');

for(var i=1; i<=10; i++){
  let el = document.createElement('h5');
  el.innerText = i;
  sampleList.append(el);
}

listTrigger.addEventListener('click', ()=> {sampleList.classList.toggle('active');});
.topFloatBar{
    position:fixed;
    width:100%;
    top: 0;
    z-index:5;
    text-align:center;
    background-color: #e3e3e3;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    cursor:pointer;
  }

    #sampleNumberList {
    position: absolute;
    width: 100%;
    overflow:hidden;
    height: auto;
    transform: scale(0);
    transition: transform 0.5s ease-in-out;
    transform-origin: top;
  }

.active{transform: scale(1) !important;}
<div class="topFloatBar" id="topSampleNum" >
    <h2 id="mainNumber">#1</h2>
    <div id="sampleNumberList"></div>
</div>

答案 1 :(得分:0)

使用jQuery slideToggle()平滑切换那些h5。

请参阅演示:JSFiddle

$('#clickableDiv').click(function() {
  $('h5').slideToggle();
});
#sampleNumberList>h5 {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div style='background:red'>
  <h2 id='mainNumber'> #1 </h2>
  <div id='clickableDiv' style='background:yellow'> Click Me </div>
  <div id='sampleNumberList' style='background:blue'>
    <h5> #1 </h5>
    <h5> #2 </h5>
    <h5> #3 </h5>
  </div>
</div>