我有一个按钮,想要在两个“功能”之间切换。我希望它可以切换菜单的打开和关闭状态
我想在第一次点击时添加onclick="openNav()"
,然后在第二次点击时添加onclick="closeNav()"
html
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="openNav()"></button>
我不确定执行此操作的最佳方法,如果鳕鱼位于两个单独的按钮上,那么它们会起作用。
编辑:我正在使用Wordpress,所以所有的javascript都位于一个单独的.js文件中
答案 0 :(得分:1)
您可以创建一个toggleNav
函数,该函数将通过使用如下所示的布尔值来在执行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>
答案 1 :(得分:1)
您通常会遇到类似这样的情况:
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="toggleNav()"></button>
还有JS:
var navOpen = false;
function toggleNav(){
navOpen = !navOpen
// Do conditional show hide here based on navOpen
}
答案 2 :(得分:1)
您可以在两个函数的末尾更改元素的onclick
。
let btn = document.getElementById('nav-icon');
function openNav(){
console.log('openNav called');
btn.onclick = closeNav
}
function closeNav(){
console.log('closeNav called');
btn.onclick = openNav
}
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="openNav()"></button>
答案 3 :(得分:1)
只需在每个函数中添加一行:
在openNav()
中:
document.getElementById("nav-icon").setAttribute("onclick", "closeNav()");
在closeNav()
中:
document.getElementById("nav-icon").setAttribute("onclick", "openNav()");
答案 4 :(得分:1)
也许您可以根据一些标志值调用函数:
var flag = true;
var navBtn = document.querySelector('#nav-icon');
navBtn.addEventListener('click', function(btn){
if(flag) openNav();
else closeNav();
flag = !flag;
});
function openNav(){
console.log('Open');
}
function closeNav(){
console.log('Close');
}
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button">Click</button>