简体   繁体   English

直到第二次点击,Javascript内容才会显示

[英]Javascript Content doesn't display until second click

When I first load the page it takes two clicks to show the content but then after that, every click will either show or hide. 当我第一次加载页面时,只需点击两下即可显示内容,但之后,每次点击都会显示或隐藏。 So it works... just not right away. 所以它有效......就在不久之前。

 function navClick() { var content = document.querySelector('.dropdown-content'); if (content.style.display == 'none') { content.style.display = 'block'; } else { content.style.display = 'none'; } }; 
 .dropbtn { position: relative; float: right; font-size: 35px; color: #fff; margin-top: -50px; padding-bottom: 15px; ; margin-right: 30px; cursor: pointer; z-index: 2; display: nne; } 
 <a class="dropbtn" onclick="navClick()"><i class="ion-ios-menu"></i></a> <div class="dropdown col"> <ul class="dropdown-content"> <li><a href="eguitarindex.html">Guitars</a></li> <li><a href="drumsindex.html">Drums</a></li> <li><a href="ampsindex.html">Amps</a></li> <li><a href="gearindex.html">Gear</a></li> <li><a href="#featured">Featured</a></li> <li class="find-us"><a href="#find-us">Find Us</a></li> </ul> </div> 

What is happening here and how can I make the function work the first time a user clicks? 这里发生了什么,如何在用户第一次点击时使该功能正常工作?

The problem is that content.style.display isn't defined, so it isn't none when you click, so it is set as none , next time through it is none so it changes to block . 问题是content.style.display没有定义,因此当你点击它时它不是none ,所以它被设置为none ,下次通过它是none所以它变为block I would recommend using classList.toggle instead though: 我建议使用classList.toggle代替:

 function navClick() { var content = document.querySelector('.dropdown-content'); content.classList.toggle('hidden'); }; 
 .hidden { display: none; } 
 <a class="dropbtn" onclick="navClick()">Toggle Menu</a> <div class="dropdown col"> <ul class="dropdown-content"> <li><a href="eguitarindex.html">Guitars</a></li> <li><a href="drumsindex.html">Drums</a></li> <li><a href="ampsindex.html">Amps</a></li> <li><a href="gearindex.html">Gear</a></li> <li><a href="#featured">Featured</a></li> <li class="find-us"><a href="#find-us">Find Us</a></li> </ul> </div> 

I think it happens because ul tag doesn't have style attribute, so you can add it as follow: 我认为这是因为ul标签没有style属性,所以你可以添加如下:

<ul class="dropdown-content" style="display: block;">

You can also change in css: 你也可以改变css:

display: nne;

to

display: none;

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

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