【发布时间】:2021-01-02 01:57:08
【问题描述】:
基于这篇文章 - How to open dropdown button by clicking on text?
当您将链接“工具”悬停在此脚本之外但成功时,我正在尝试添加此下拉效果(我想同时保持 onclick)。有人可以帮助我吗?我敢肯定这很容易,但对不起,我不是 JS 专家。花了几个小时没有找到任何解决方案:(
非常感谢您的帮助。
JS:
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
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');
}
}
}
}
我尝试添加这个 -
document.getElementByClassName(".dropbtn").onmouseenter = function(){
document.getElementByClassName("dropdown-content").classList.contains("show");
}
CSS
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
button.dropbtn{
font-weight: 700;
background:none;
border:none;
padding:0;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
HTML
<div>
<button onclick="myFunction()" class="dropbtn">Tools</button>
<ul id="myDropdown" class="dropdown-content">
<li><a href="#">Blok 1</a></li>
<li><a href="#">Blok 1</a></li>
<li><a href="#">Blok 1</a></li>
</ul>
</div>
【问题讨论】:
-
欢迎来到 SO。你试过自己写吗?如果是这样,请向我们展示您的代码,这将有助于我们提供解决方案。
-
嗨,Ambrish,谢谢! :) 我编辑了我的帖子。
标签: javascript hyperlink menu hover dropdown