当然,以下是一个使用JavaScript制作的简单导航点击效果的示例代码。这个效果会在点击导航项时,高亮显示当前选中的项,并且平滑滚动到对应的页面部分。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Navigation Click Effect</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav>
<ul>
<li><a href="#section1" class="nav-link">Section 1</a></li>
<li><a href="#section2" class="nav-link">Section 2</a></li>
<li><a href="#section3" class="nav-link">Section 3</a></li>
</ul>
</nav>
<section id="section1">Section 1 Content</section>
<section id="section2">Section 2 Content</section>
<section id="section3">Section 3 Content</section>
<script src="script.js"></script>
</body>
</html>
/* styles.css */
body {
font-family: Arial, sans-serif;
}
nav {
position: fixed;
top: 0;
width: 100%;
background-color: #333;
}
nav ul {
list-style-type: none;
padding: 0;
display: flex;
justify-content: center;
}
nav ul li {
margin: 0 10px;
}
nav ul li a {
color: white;
text-decoration: none;
padding: 10px 20px;
transition: background-color 0.3s;
}
nav ul li a.active {
background-color: #555;
}
section {
height: 100vh;
padding-top: 60px; /* To avoid content being hidden behind the fixed navbar */
}
#section1 { background-color: #f4f4f4; }
#section2 { background-color: #e4e4e4; }
#section3 { background-color: #d4d4d4; }
// script.js
document.addEventListener('DOMContentLoaded', function() {
const navLinks = document.querySelectorAll('.nav-link');
navLinks.forEach(link => {
link.addEventListener('click', function(event) {
event.preventDefault(); // Prevent the default anchor behavior
// Remove active class from all links
navLinks.forEach(link => link.classList.remove('active'));
// Add active class to the clicked link
this.classList.add('active');
// Scroll to the section
const targetId = this.getAttribute('href');
const targetSection = document.querySelector(targetId);
targetSection.scrollIntoView({ behavior: 'smooth' });
});
});
});
active
类,然后为点击的链接添加active
类。scrollIntoView
方法平滑滚动到对应的页面部分。这个示例展示了如何使用JavaScript来实现一个简单的导航点击效果,包括高亮显示当前选中的导航项和平滑滚动到对应的页面部分。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云