【发布时间】:2018-11-01 02:31:03
【问题描述】:
我试图通过 w3schools.com 上的 this 教程实现使用 Javascript 打开和关闭下拉菜单的方法。虽然“显示”下拉菜单的功能有效,但关闭它的功能无效。此外,在此代码旁边没有任何解释来解释为什么它应该工作,从而使其难以调试。
/* 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 menu 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');
}
}
}
}
因此,我的问题是,
1) 教程中的代码是否应该用于关闭下拉菜单。 (已回答)
2) 有人可以澄清一下这应该如何/为什么起作用,以便我自己和未来遇到相同教程和问题的新手清楚吗? (未回答)
编辑(我的尝试):
HTML:
<div class="sharedown">
<p onclick="shareVis()" class="sharebtn">  Share</p>
<div id="mySharedown" class="sharedown-content">
<a href="#">Self</a>
<p>User</p><input type="text" name="user-name" placeholder="Share to">
<a href="#">Community</a>
</div>
</div>
JS:
function shareVis() {
document.getElementById("mySharedown").className = "show";
}
window.onclick = function(event) {
if (!event.target.matches('sharebtn')) {
var sharedowns = document.getElementsByClassName("sharedown-content");
var i;
for (i = 0; i < sharedowns.length; i++) {
var openSharedown = sharedowns[i];
if (openSharedown.classList.contains('show')) {
openSharedown.classList.remove('show');
}
}
}
}
CSS:
/* Share dropdown menu */
p.sharebtn {
color: darkgrey;
font-family:calibri;
padding: 0px;
margin: 0px;
font-size: 12;
border: none;
cursor: pointer;
display: inline;
}
/* Dropdown button on hover & focus */
p.sharebtn:hover, p.sharebtn:focus {
color: grey;
}
/* The container <div> - needed to position the dropdown content */
.sharedown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.sharedown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 100px;
box-shadow: 0 2px 4px 1px #C4E3F5;
z-index:1; /* place dropdown infront of everything else*/
}
.sharedown-content a {
color: black;
padding: 5px 5px;
text-decoration: none;
display: block;
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-
content container when the user clicks on the dropdown button) */
.show {display: block;
position: absolute;
background-color: #f1f1f1;
min-width: 100px;
box-shadow: 0 2px 4px 1px #C4E3F5;
opacity: 1;
z-index:1;}
【问题讨论】:
-
请提供 HTML 以告诉您确切的问题在哪里?因为 w3schools 中的示例功能齐全
-
浏览器中的调试控制台是什么意思?
-
控制台没有错误
-
你能添加你的css吗?
-
document.getElementById("mySharedown").className = "show";覆盖类名。它不再有sharedown-content类,所以当window.onclick触发时,sharedowns变量将为空。
标签: javascript html web