gpt4 book ai didi

Javascript 和 HTML - 添加下拉菜单,我在这里做错了什么?

转载 作者:行者123 更新时间:2023-11-28 06:12:04 28 4
gpt4 key购买 nike

我刚刚从 W3Schools 复制了下拉菜单并更改了它们的类名/id,以便我可以在我的代码中使用它。

我有两件事:

  1. 我做错了什么?

  2. for 循环而不是 for-in 有什么作用?加一的目的是什么?

HTML:

<body>
<nav class = "header">
<div id = "logo"> <a href = "ee"/> </a> </div>
<ul>
<li class = "nav_li" id= "cata_li" onclick = "myFunction()">
<a class ="nav_a" href="ee"> Find <br/> Poop</a>
<ul class = "dropdown_menu">
<li> <a href = "#"> Horse poop </a> </li>
</ul>
</li>

JavaScript:

function myFunction() {
document.getElementById("cata_li").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches(".nav_li")) {
var dropdowns = document.getElementsByClassName("dropdown_menu");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}

CSS(我确定这里没有问题,我的 CSS 看起来还是一样):

 .header > ul{
display: inline-block;
position: absolute;
top: 0px;
left: 250px;
}

.header> ul > li{
display: inline-block;
list-style: none;
vertical-align: top;
}

.dropdown_menu{
position: absolute;
display: none;
z-index: 40;
top:50px;
left:0;
background-color: #222;
width: 300px;
list-style: none;
padding: 10px;
}

最佳答案

这里有两个问题,在你的 nav_a 中是一个 anchor 元素,它的默认操作是导航到 href 值,这里你需要阻止它。

此外,matches 函数只会检查当前元素,您需要检查点击是否发生在 nav_li 元素内,因此请使用 .closest()相反

function myFunction(event) {
event.preventDefault();
document.querySelector("#cata_li .dropdown_menu").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.closest(".nav_li")) {
var dropdowns = document.getElementsByClassName("dropdown_menu");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.header > ul {
display: inline-block;
position: absolute;
top: 0px;
left: 250px;
}
.header> ul > li {
display: inline-block;
list-style: none;
vertical-align: top;
}
.dropdown_menu {
position: absolute;
display: none;
z-index: 40;
top: 50px;
left: 0;
background-color: #222;
width: 300px;
list-style: none;
padding: 10px;
}
.dropdown_menu.show {
display: block;
}
<nav class="header">
<div id="logo">
<a href="ee"></a>
</div>
<ul>
<li class="nav_li" id="cata_li" onclick="myFunction(event)">
<a class="nav_a" href="ee"> Find <br/> Poop</a>
<ul class="dropdown_menu">
<li> <a href="#"> Horse poop </a>
</li>
</ul>
</li>
</ul>
</nav>

关于Javascript 和 HTML - 添加下拉菜单,我在这里做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110395/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com