【发布时间】:2022-01-12 07:37:58
【问题描述】:
我正在使用 nextjs 应用程序。我只是想制作一个下拉菜单。
这是我的完整代码:
import React from 'react'
import Link from 'next/link'
import styles from './header.module.css'
const Header = () => {
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
const myFunction =()=>{
document.getElementById(styles.myDropdown).classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
if (typeof window !== "undefined") {
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');
}
}
}
}
}
return (
<div className={styles.header}>
<div className={styles.logoLink}>
<img src="images/itacs.png" alt="" className={styles.logo} />
</div>
<div className={styles.services}>
<ul>
<li><Link href="/page">Docs</Link></li>
<li><Link href="/page">Learn</Link></li>
<li><Link href="/page">Projects</Link></li>
<li><Link href="/page">Blog</Link></li>
<div className={styles.dropdown}>
<button onClick={myFunction} className={styles.dropbtn}>Dropdown</button>
<div id={styles.myDropdown} className={styles.dropdownContent}>
<a href="/">Link 1</a>
<a href="/">Link 2</a>
<a href="/">Link 3</a>
</div>
</div>
</ul>
</div>
<form action="" className={styles.headerForm}>
<a href="/" className={styles.logIn}>Log In</a>
<a href="/" className={styles.getStarted}>Get Started</a>
</form>
</div>
)
}
export default Header
这里我刚刚在div的id中添加了classlist! 当按钮被单击为下拉菜单时,我试图显示下面的 div。 我无法弄清楚这一点!
对于任何想知道 css 文件中存在什么的人:
/* dropdown */
/* Dropdown Button */
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdownContent {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdownContent a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdownContent a:hover {background-color: #ddd}
/* 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;}
任何帮助将不胜感激!
【问题讨论】:
-
styles.dropdownContent和{styles.myDropdown}设置在哪里?如果您使用变量在标记中设置 id 和 className,您可能应该在脚本中使用相同的变量,例如 document.getElementById(${styles.myDropdown}).classList.toggle("show");
标签: javascript reactjs next.js typeerror dropdown