繁体   English   中英

它在第一次点击时不起作用,但在第二次点击时起作用。 如何解决?

[英]It doesn't work on the first click, but does on the second one. How to fix that?

所以我有这样的 function ,它在第一次点击时不起作用,但在第二次点击时起作用。 如何解决?

 let coll = document.getElementsByClassName('collection'); let dis = document.getElementsByClassName('display'); document.getElementById("menu-btn1").addEventListener("click", function() { if(coll[0].style.display == 'none') { coll[0].style.display = 'block'; dis[0].style.display = 'none'; } else { coll[0].style.display = 'none'; } });
 .collection { width: 80vh; height: 85vh; background-color: blue; display: none; grid-column: 4 / 10; grid-row: 2 / 9; justify-self: center; z-index: 3; }
 <div class="collection"></div>

(是的 - 我之前一直在寻找这样的案例,但大部分是 jQuery,我不明白,请帮忙)

因为coll[0].style.display = 'block'; 搜索内联样式并添加display: none; 在 css class 上,如果您正在检查 styles,您需要像这样添加内联样式:

<div class="collection" style="display:none;"></div>

在这里您可以看到带有正确 styles 的片段

 let coll = document.getElementsByClassName('collection'); let dis = document.getElementsByClassName('display'); document.getElementById("menu-btn1").addEventListener("click", function() { if(coll[0].style.display == 'none') { coll[0].style.display = 'block'; //dis[0].style.display = 'none'; } else { coll[0].style.display = 'none'; } });
 .collection { width: 80vh; height: 85vh; background-color: blue; grid-column: 4 / 10; grid-row: 2 / 9; justify-self: center; z-index: 3; }
 <div class="collection" style="display:none;"> </div> <button id="menu-btn1">Toggle</button>

我建议清理您的代码并使用 class 切换来隐藏和显示它

你的 CSS:

.collection {
    width: 80vh;
    height: 85vh;
    background-color: blue;

    grid-column: 4 / 10;
    grid-row: 2 / 9;
    justify-self: center;
    z-index: 3;
}
.hidden {
    display: none;
}

您的 HTML:

<div class="collection hidden"></div>
<div class"display"></div> <!--I was assuming your .display element was visible at first and you wanted to hide it afterwards-->

你的 JS:

let coll = document.getElementsByClassName('collection');
let dis = document.getElementsByClassName('display');

document.getElementById("menu-btn1").addEventListener("click", function() {
  coll[0].classList.toggle("hidden");
  dis[0].classList.toggle("hidden");
});

这样你的代码就更干净了,因为你为display: none; 当您应用“显示:无”时,您正在避免有关 CSS 中选择器 styles 层次结构的棘手问题; 到该 class 的所有元素,但仅尝试更改该 class 中的元素之一的显示

我认为您共享的代码不完整,我在 html menu-btn1display中看不到这些类,您可以将代码上传到 github 例如或您喜欢的任何其他工具

暂无
暂无

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

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