如何求解未被发现的typeerror-无法阅读null的属性“ addeventListener”
2019-09-11
105
每当我点击汉堡元素时,什么都没有发生
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="GNG.js"></script>
<link rel="stylesheet" href="stylesheet/style.css">
<title>GnG</title>
</head>
<body>
<nav>
<div class="navbar-brand">
George n George
</div>
<!-- <a class="navbar-brand" href="#"></a> -->
<ul class="nav-links">
<li class= "nav-active" ><a href="#">Home </a></li>
<li ><a href="#">Contact</a> </li>
<li ><a href="#">About us</a></li>
<li ><a href="#">Laundry</a></li>
<li ><a href="#">Clothes </a></li>
<li ><a href="#">Business</a></li>
</ul>
<div class="burger">
<div class="_line1"></div>
<div class="_line2"></div>
<div class="_line3"></div>
</div>
</nav>
</body>
</html>
我的 css 文件
/*======================== styling the navbaar==========================*/
.burger div{
width: 25px;
height: 1px;
background-color: whitesmoke;
margin: 5px;
}
.burger{
display: none;
cursor: pointer;
}
@media screen and (max-width: 1024px){
.nav-links{
width: 40%
}
}
@media screen and (max-width: 600px){
body{
overflow-x: hidden;
}
.nav-links{
position: absolute;
right: 0px;
height: 92vh;
top: 8vh;
background-color: rgb(21, 19, 43);
display: flex;
flex-direction: column;
align-items: center;
width: 70%;
transform: translateX(100%);
transition: transform 0.9s ease-in;
}
.nav-links li{
opacity: 0;
}
.burger{
display: block;
}
}
.nav-active{
transform: translateX(0%)
}
@keyframes _navLinkFade{
from{
opacity: 0;
transform: translateX(50px)
}
to{
opacity: 1;
transform: translateX(0px)
}
}
/* ======================== navbar end==================================*/
和 javascript
const navSlide = () => {
const burger = document.querySelector('.burger');
const nav = document.querySelector('.nav-links');
// const navLinks = document.querySelectorAll('.nav-links li');
burger.addEventListener('click', () =>
{
nav.classList.toggle('nav-active');
navLinks.forEach((link, index) =>
{
link.style.animations = `navLinkFade 0.5s ease forward ${ index / 7 + 1.5 }s`;
});
});
}
navSlide();
每当我点击汉堡元素时,菜单应该从右侧淡入,但查看控制台时,我发现 addEventListener 不起作用。尝试使用 addeventListner 的其他项目并得到同样的错误。以为我的浏览器需要更新,我这样做了但无济于事
1个回答
在关闭
</body>
标签之前移动您的脚本标签或在
DOMContentLoaded
事件之后调用您的函数;
const navSlide = () => {
const burger = document.querySelector(".burger");
const nav = document.querySelector(".nav-links");
// const navLinks = document.querySelectorAll('.nav-links li');
burger.addEventListener("click", () => {
nav.classList.toggle("nav-active");
navLinks.forEach((link, index) => {
link.style.animations = `navLinkFade 0.5s ease forward ${index / 7 +
1.5}s`;
});
});
};
document.addEventListener("DOMContentLoaded", navSlide);
2019-09-11