简体   繁体   English

我怎样才能做一个切换 function

[英]How can i make a toggle function

I am trying to make a toggle button on a website that I am making that activates a javascript navbar when pressed then when pressed a second time the navbar retracts out of sight.我正在尝试在我正在制作的网站上制作一个切换按钮,该按钮在按下时激活 javascript 导航栏,然后在第二次按下时导航栏缩回视线之外。 I have got the code working to where the navbar pops out when the button is pressed but I can't work out how to make the navbar retract.我已经将代码工作到按下按钮时导航栏弹出的位置,但我不知道如何让导航栏缩回。

function tog() {

  var x = 0;
  
  if (x == 0) {
    document.getElementById("Sidenav").style.height = "450px";
    document.getElementById("main").style.marginTop = "0px";
    document.body.style.backgroundColor = "rgba(0,0,0,1)";
    x = 1;
  }
  
  else {
    document.getElementById("Sidenav").style.height = "0";
    document.getElementById("main").style.marginTop= "0";
    document.body.style.backgroundColor = "white";
    x = 0;
  }
  
};

This is the javascript that controls the toggle function, and the button is:这是控制切换 function 的 javascript,按钮为:

<div class="panel"><button class='pan' onclick='tog()'></button></div>

Any input as to where I am going wrong would be much appreciated.任何关于我哪里出错的意见将不胜感激。

Try this, the logic is: x equals 0?试试这个,逻辑是:x等于0? then x = 1 else x = 0.那么 x = 1 否则 x = 0。

 var x = 0; function tog() { x = x == 0? 1: 0; if (x == 0) { console.log(x) } else if(x == 1){ console.log(x) } };
 <div class="panel"><button class='pan' onclick='tog()'>Toggle!</button></div>

You could do something like this.你可以做这样的事情。

 var x = 0; function toggle() { if (x === 0) { document.getElementById("Sidenav").style.height = "150px"; document.body.style.backgroundColor = "rgba(0,0,0,1)"; x = 1; } else { document.getElementById("Sidenav").style.height = "0"; document.body.style.backgroundColor = "white"; x = 0; } };
 #Sidenav { width: 400px; border: 1px solid #9c0000; border-radius: 10px; height: 0; }
 <div id="Sidenav"></div> <button onclick="toggle()">toggle</button>

let sideNav = document.getElementById("Sidenav");
function toggle(){
    sideNav.classList.toggle("open");
    document.body.classList.toggle("open-bg");
}


.open{
    height: 450px;
}

.open-bg{
    background-color: rgba(0, 0, 0, 1);
}

make use of toggle method for classList to remove and add class alternately when button is clicked.当单击按钮时,使用 classList 的切换方法交替删除和添加 class。

and try not to change css attributes too much in JavaScript.并尽量不要在 JavaScript 中过多地更改 css 属性。 I mean it's not bad but it makes your code look kinda big.我的意思是它还不错,但它让你的代码看起来有点大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM