如何实现Javascript slideUp / slideDown ?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (293)

在html中有以下代码:

<div id = "box">Show / Hide</div>
  <button onclick="slideUp('box');">Slide Up</button>
  <button onclick="slideDown('box');">Slide Down</button>
body{
  background:grey;
}

#box{
  width:400px;
  height:400px;
  background:orange;
  margin:0 auto;
  margin-top:3%;
  overflow:hidden;
}
function slideUp(el) {
  var elem = document.getElementById(el);
  elem.style.transition = "all 2s ease-in-out";
  elem.style.height = "0px";
}
function slideDown(el) {
  var elem = document.getElementById(el);
  elem.style.transition = "all 2s ease-in-out";
  elem.style.height = "400px";
}
提问于
用户回答回答于

可以创建CSS :

var elem = document.getElementById("box");
function slide() {
  elem.classList.toggle('hide');
}
.box {
  width: 400px;
  height: 400px;
  overflow: hidden;
  background: orange;
  margin: 0 auto;
  transition: all 0.4s ease-in-out;
}
.hide {
  height: 0;
}
<button onclick="slide();">Slide Toggle</button>
<div id="box" class="box">Show / Hide</div>

用户回答回答于

通过CSS样式表将转换到#box:

 #box {
  -webkit-transition: all 2s ease-in-out;
  -ms-transition: all 2s ease-in-out;
  transition: all 2s ease-in-out;
  width:400px;
  height:400px;
  background:orange;
  margin:0 auto;
  margin-top:3%;
  overflow:hidden;
}
  var Dropdown = function(el) {

      var is_open = false;
      var elem = document.querySelector(el);  
      // in case you cannot set transition via stylesheet 
      elem.style.transition = "all 2s ease-in-out";

      function slideUp() {
        elem.style.height = "0px";     
        is_open = false;
      }
      function slideDown() {
        elem.style.height = "400px";
        is_open = true;
      }
      function init() {
        if(is_open) {
          slideUp();
        }else{
          slideDown();
        }
      }
      return {
        init : init
      }
  };

  myDropdown = Dropdown('#box');
  document.querySelector('#your-button').addEventListener('click',  myDropdown.init);

扫码关注云+社区

领取腾讯云代金券