下拉菜单短暂显示,然后消失



我正在为我的Chrome扩展程序创建一个下拉菜单。 有一些 Javascript 代码会导致菜单显示,但是当我单击按钮时,下拉菜单只显示一瞬间然后消失(看起来像闪烁效果(。任何帮助将不胜感激。 谢谢!

欢迎.html

<form>
<div class="dropdown">
<button id="dropdownbtn" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
<input type="submit" id="signup" value="Get Started">
</form>

界面.js

//Add dropdown
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("dropdownbtn").addEventListener("click", myFunction);
//  document.getElementById("dropdownbtn").addEventListener("mouseout", myFunction);
});
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction()  {
console.log("in toggle");
document.getElementById("myDropdown").classList.toggle("show");
}

manifest.json

{
"manifest_version": 2,
"name": "Hello World",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"browser_action": {
"default_icon": "./icons/icon.png",
"default_popup":  "account.html"
},
"manifest_version": 2,
"content_scripts": [
{
"css": ["style.css"],
"js": [ "content.bundle.js", "interface.js" ],
"matches": ["<all_urls>"]
}
]
}
document.getElementById("dropdownbtn").addEventListener("click", myFunction);
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction(e)  {
e.preventDefault();
console.log("in toggle");
document.getElementById("myDropdown").classList.toggle("show");
}

工作小提琴: https://jsfiddle.net/uzps6Lr1/

也许有人可以解释为什么,但这似乎是因为你正在使用<form>元素来包装按钮。删除它并重新运行上述内容似乎可以无限期地保持下拉列表处于活动状态。也许它的书面方式假设单击下拉列表正在提交表单,但没有什么可提交的?

最新更新