嗨,我正在开发我自己的组合与HTML CSS和JavaScript,我添加了一些过渡动画。一切正常,直到我点击另一个超链接,那里的转换运行良好,但之后我的页面变成空白,并显示以下错误:“无法获得未定义”。
index.html:只是一个带有一些超链接的简单主页,我的CSS和JavaScript链接正确。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="transitions.css">
<title>Document</title>
</head>
<body>
<div class="transition transition-1 is-active"></div>
<section>
<ul>
<li><a href="/"><span>HOME</span></a></li>
<li><a href="about.html"><span>ABOUT</span></a></li>
<li><a href="contact.html"><span>CONTACT</span></a></li>
<li><a href=""><span>GITHUB</span></a></li>
</ul>
<h1>Mateo Ghidini | Web Developer</h1>
</section>
<script src="main.js"></script>
</body>transitions.css:
.transition-1{
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
z-index: 101;
background-color: var(--dark);
opacity: 0;
pointer-events: none;
transition: 0.5s ease-out;
}
.transition-1.is-active{
opacity:1;
pointer-events: all;
}
.transition-2{
position:fixed;
top:0;
left:-100%;
width:100%;
bottom:0;
z-index: 101;
background-color: var(--dark);
pointer-events: none;
transition: 0.5s ease-out;
}
.transition-2.is-active{
left:0px;
}
.transition-3{
position:fixed;
top:100%;
left:0;
right:0;
height:100%;
z-index: 101;
background-color: var(--dark);
pointer-events: none;
transition: 0.5s ease-out;
}
.transition-3.is-active{
top:0px;
}main.js:
window.onload=() =>{
const transition_el = document.querySelector('.transition');
const anchors = document.querySelectorAll('a');
setTimeout(()=>{
transition_el.classList.remove('is-active');
}, 500);
for(let i = 0; i<anchors.length; i++){
const anchor = anchors[i];
anchor.addEventListener('click', e =>{
e.preventDefault();
let target = e.target.href;
transition_el.classList.add('is-active');
setTimeout(()=>{
window.location.href = target;
},500);
});
}
}我希望有人能帮助解决这个问题,因为我对这个错误一无所知。
发布于 2021-04-21 13:11:54
问题是e.target.href中的目标是<span>标记,而不是没有href的<a>标记。
从链接中删除跨度是可行的,例如使用currentTarget而不是target。
anchor.addEventListener('click', e => {
e.preventDefault();
let target = e.currentTarget.href;
// etc...
});发布于 2021-04-21 13:04:27
事件参数的正确属性应为
e.currentTarget.hrefmain.js
window.onload = () => {
const transition_el = document.querySelector(".transition");
const anchors = document.querySelectorAll("a");
setTimeout(() => {
transition_el.classList.remove("is-active");
}, 500);
for (let i = 0; i < anchors.length; i++) {
const anchor = anchors[i];
anchor.addEventListener("click", (e) => {
e.preventDefault();
let target = e.currentTarget.href;
transition_el.classList.add("is-active");
setTimeout(() => {
window.location.href = target;
}, 500);
});
}
};https://stackoverflow.com/questions/67188920
复制相似问题