我有一个按钮,想要在两个“功能”之间切换。我希望它切换我的菜单以打开和关闭
我想在第一次单击时添加onclick="openNav()"
,然后在第二次单击上添加onclick="closeNav()"
html
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="openNav()"></button>
我不确定执行此操作的最佳方法,如果鳕鱼在两个单独的按钮上,它们会起作用。
编辑:我使用的是Wordpress,所以所有的javascript都放在一个单独的.js文件中
最佳答案
您可以创建一个toggleNav
函数,该函数将通过使用如下所示的 bool(boolean) 值来在执行openNav
和closeNav
函数之间进行替换:
let opened = false; // set the nav as closed by default
function toggleNav() {
if(!opened) { // if opened is false (ie nav is closed), open the nav
openNav()
} else { // else, if opened is ture (ie nav is open), close the nav
closeNav();
}
opened = !opened; // negate boolean to get opposite (t to f, and f to t)
}
function openNav() {
console.log("Opened Nav");
}
function closeNav() {
console.log("Closed Nav");
}
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="toggleNav()">Toggle Nav</button>