所以我在尝试创建点击下拉菜单时遇到了问题。 首先,有一个我正在处理的真实站点。 https://socialmanagement.000webhostapp.com/ 在 736px 宽度下,菜单将变成一个按钮。问题是在移动设备上它确实有问题。如果您在手机上单击它,它会自动将您带到菜单中最后一个按钮的“href”,即使它没有显示。此外,菜单不会在再次单击“主页”按钮后下降
我需要下拉到一个菜单,我点击按钮(按钮将保持在相同的位置,而不是现在它上升的位置)并且它会一直停留直到用户再次点击它。 非常感谢任何建议
HTML:
<div class="navbar" id="myTopnav" >
<div class="dropup">
<a href="javascript:void(0);" class="icon" onclick="myFunction()"> <img src="images/Icons/home.png" /> </a>
<div class="dropup-content" >
<a href="#home" > <img src="images/Icons/home.png" /> Home</a>
<a href="#news"> <img src="images/Icons/about.png" /> News</a>
<a href="#contact"> <img src="images/Icons/info.png" /> Contact</a>
<a href="#home"> <img src="images/Icons/menu.png" /> Home</a>
<a href="#news"> <img src="images/Icons/pic.png" /> Newssssssssssss</a>
<a href="#contact"> <img src="images/Icons/about.png" /> Contact</a>
</div>
</div>
</div>
SCRIPT(我在这里得到的第一个脚本很糟糕,所以我不得不将其更改为这个,仍然无法从移动设备上关闭它):
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.icon')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
最佳答案
已编辑:
首先,在您提供的 HTML 代码中,没有 myDropdown
元素。因此,首先我们需要将 id 添加到 dropup-content
元素中。然后,我们可以在单击 a
或在您的情况下单击图标时切换 show
类。所以,这里是:
HTML:
<div class="navbar" id="myTopnav" >
<div class="dropup">
<!-- You don't need javascript void here, we just won't include href.-->
<a class="icon" onclick="myFunction()"> <img src="images/Icons/home.png" /> </a>
<!-- We add id="myDropdown" to the dropup-content element.-->
<div class="dropup-content" id="myDropdown">
<a href="#home" > <img src="images/Icons/home.png" /> Home</a>
<a href="#news"> <img src="images/Icons/about.png" /> News</a>
<a href="#contact"> <img src="images/Icons/info.png" /> Contact</a>
<a href="#home"> <img src="images/Icons/menu.png" /> Home</a>
<a href="#news"> <img src="images/Icons/pic.png" /> Newssssssssssss</a>
<a href="#contact"> <img src="images/Icons/about.png" /> Contact</a>
</div>
</div>
</div>
脚本:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show")
}
// This is all you need to toggle on/off the menu,
// no need of that extra function with a for loop that you have in your code.
当然,这是不言而喻的,您必须按照您希望的方式编辑 CSS 中的 show
类。
至于另一个问题,如何将菜单固定在同一位置,您只需将 position: absolute
添加到 CSS 中的该元素,使用 top/left/right/bottom
你喜欢的坐标,并给它一个 z-index: 2(or higher)
以确保它在顶部每一个其他元素。希望这能解决您的问题。
关于javascript - 完整的下拉菜单 OnClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036570/