首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js制作导航点击效果代码

当然,以下是一个使用JavaScript制作的简单导航点击效果的示例代码。这个效果会在点击导航项时,高亮显示当前选中的项,并且平滑滚动到对应的页面部分。

HTML结构

代码语言:txt
复制
<!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>

CSS样式

代码语言:txt
复制
/* 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; }

JavaScript代码

代码语言:txt
复制
// 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' });
        });
    });
});

解释

  1. HTML结构:创建了一个简单的导航栏和三个部分(section),每个部分都有一个唯一的ID。
  2. CSS样式:定义了导航栏的样式,并设置了点击时的高亮效果。
  3. JavaScript代码
    • 监听所有导航链接的点击事件。
    • 阻止默认的锚点跳转行为。
    • 移除所有链接的active类,然后为点击的链接添加active类。
    • 使用scrollIntoView方法平滑滚动到对应的页面部分。

这个示例展示了如何使用JavaScript来实现一个简单的导航点击效果,包括高亮显示当前选中的导航项和平滑滚动到对应的页面部分。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券