Javascript slideUp/slideDown/tek buton


Bir problemi çözmekte zorlanıyorum. 2 butonum var, biri slideUp için diğeri slideDown için. Yapmak istediğim şey, 2 buton yerine bir butonun geçiş yapması.

Teşekkürler.

HTML'de bu kodum var:

<div id = "box">Show / Hide</div>
  <button onclick="slideUp('box');">Slide Up</button>
  <button onclick="slideDown('box');">Slide Down</button>

ve benim bu CSS kodum var:

body{
  background:grey;
}

#box{
  width:400px;
  height:400px;
  background:orange;
  margin:0 auto;
  margin-top:3%;
  overflow:hidden;
}

ve benim javascript kodum bu:

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";
}

Cevap #1

CSS class’ını height:0 kuralıyla oluşturabilir ve bu class’ı JS ile değiştirebilirsiniz:

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>

Cevap #2

CSS özelliklerini bir sınıfa koyun, sınıfı öğenize ekleyin ve ardından öğenin yüksekliğini etkileyen sınıfı classList.toggle() kullanarak açıp kapatın

function slideToggle(el) {
  var elem = document.getElementById(el);
  elem.classList.toggle("open");
}
body{
  background:grey;
}

#box{
  width:400px;
  background:orange;
  margin:0 auto;
  margin-top:3%;
  overflow:hidden;
}

.slider {
    transition:all 2s ease-in-out;
    height:0px;
}
.slider.open {
    height:400px;
}
<div id = "box" class="slider">Show / Hide</div>
<button onclick="slideToggle('box');">Slide</button>