使用Javascript切换折叠后的隐藏按钮

时间:2018-07-29 11:04:55

标签: javascript html button collapsable

我试图在按下“可折叠”按钮后将其隐藏。

activities.html:

<button class="collapsible"> <i class="fa fa-angle-down"></i></a></button>

Controller.js:

    var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var gallery1 = this.nextElementSibling;
    if (gallery1.style.maxHeight){
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    } 
});
}

如果有人可以帮助我,我将不胜感激!

2 个答案:

答案 0 :(得分:4)

要隐藏button 并删除页面上按钮所占用的空间,请在事件处理程序中的.style.display = 'none'元素上使用button:< / p>

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");    
    
    var gallery1 = this.nextElementSibling;
    
    if (gallery1.style.maxHeight) {
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    }
    
    this.style.display = 'none';
  });
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<button class="collapsible"><a><i class="fa fa-angle-down"></i></a></button>

要保留button在页面上的空间并使它不可见,请使用.style.visibility = 'hidden'

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");    
    
    var gallery1 = this.nextElementSibling;
    
    if (gallery1.style.maxHeight) {
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    }
    
    this.style.visibility = 'hidden';
  });
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<button class="collapsible"><a><i class="fa fa-angle-down"></i></a></button>

答案 1 :(得分:2)

解决问题的最快捷方法是

<button class="collapsible" onclick="this.style.display = 'none';">