保持按钮:点击后激活

时间:2017-07-21 18:33:41

标签: html css

我是新手,所以这可能是一个愚蠢的问题,但我如何保留一个按钮:点击后有效?

我不知道这是否会改变芒果,但我有一个带有5个按钮的侧边栏,4个具有使一个div显示而其他部分隐藏的功能,另一个按钮是手风琴。

HTML

  <content class="menu">
    <button onclick="myFunction1();">Home</button>
    <br>
    <button onclick="myFunction2();">About</button>
    <br>
    <button class="accordion">Work</button>
      <content class="panel">
         <button id="submenu" class="Work1" onclick="myFunction3();">Work1</button>
      </content>
    <button onclick="myFunction4();">Contacts</button>
  </content>

CSS

content.panel {
    display: none;
}

爪哇

      function myFunction1() {
        document.getElementById("Home").style.display = "block";
        document.getElementById("About").style.display = "none";
        document.getElementById("Work1").style.display = "none";
        document.getElementById("Contacts").style.display = "none";
    }

    function myFunction2() {
      document.getElementById("Home").style.display = "none";
      document.getElementById("About").style.display = "block";
      document.getElementById("Work1").style.display = "none";
      document.getElementById("Contacts").style.display = "none";
    }

    function myFunction3() {
      document.getElementById("Home").style.display = "none";
      document.getElementById("About").style.display = "none";
      document.getElementById("Work1").style.display = "block";
      document.getElementById("Contacts").style.display = "none";
    }

    function myFunction4() {
      document.getElementById("Home").style.display = "none"; 
      document.getElementById("About").style.display = "none";
      document.getElementById("Work1").style.display = "none";
      document.getElementById("Contacts").style.display = "block";
}

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}

1 个答案:

答案 0 :(得分:1)

单击时,您可以使用jQuery向按钮添加类。更改按钮文本的颜色,添加/更改边框,添加/更改背景颜色等,

&#13;
&#13;
$('button').on('click', function(){
    $('button').removeClass('active_button');
    $(this).addClass('active_button');
});

//Home button active on page load
$(document).ready(function(){
    $('#Home').addClass('active_button');
});
&#13;
.active_button{
  background-color: #999;
}
&#13;
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<button id="Home">Home</button>
<button>About</button>
<button>Work</button>  
<button>Work1</button>
<button>Contacts</button>
&#13;
&#13;
&#13;