如何在单个按钮中添加更多功能

时间:2019-03-07 02:13:27

标签: javascript html css

我有一个按钮,我想添加两个功能,一个是打开菜单,另一个是关闭。

<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="openNav()"></button>

3 个答案:

答案 0 :(得分:0)

使用下面的代码。它使用document.getElementById()选择按钮,单击.addEventListener()进行操作(与html onclick属性相同)。

var open = false;

document.getElementById("nav-icon").addEventListener("click", function() {
  if (open) {
    closeNav();
    open = false;
  } else {
    openNav();
    open = true;
  }
});

function openNav() {
  console.log("open");

}

function closeNav() {
  console.log("close");

}
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button">Open</button>

答案 1 :(得分:0)

function toggleNav(btn) {
    var act = (-1 == btn.value.indexOf('open'))?'open':'close';
    btn.value = act + ' menu';
    doMenu(act);
};
function doMenu(act) {
    // do something based on act {'open'/'close'}
};

在HTML

<form>
    <input value="open menu" id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="toggleNav(this);" />
</form>

答案 2 :(得分:0)

如果只想切换导航,则可以使用以下内容。

BERT
var nav =  document.getElementById("nav");
function toggleNav(el){
  console.log(nav.className)
  if(nav.className.indexOf("active") !== -1) {
    //Hide by removing class     
    nav.className = nav.className.replace("active", "").trim();    
    el.innerHTML = "Show Nav";
  }else{
    nav.className += " active";
    el.innerHTML = "Hide Nav";
  }
}
#nav {display:none;}
#nav.active {display:block;}

如果您仅定位modern browsers,则可以使用classList.toggle()简化此操作