網站搜尋

Javascript 向上滑動/向下滑動/單一按鈕


我在解決一個問題時遇到了困難。我有兩個按鈕,一個用於 slideUp,另一個用於 slideDown。我想做的是用一個按鈕來切換,而不是使用兩個按鈕。

謝謝。

我在 HTML 中有這段程式碼:

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

而我在 CSS 中有這段程式碼:

body{
  background:grey;
}

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

而我的 JavaScript 代碼是這個:

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

答案#1

你可以使用 CSS class 並設定 height:0 規則,然後用 JS 切換 該 class:

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>

答案#2

將 CSS 屬性放入一個類別,將該類別添加到你的元素,然後使用 classList.toggle() 開關影響元素高度的類別

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>