0

0

如何在点击锚点链接后关闭下拉菜单而不刷新页面

心靈之曲

心靈之曲

发布时间:2025-10-26 11:55:17

|

673人浏览过

|

来源于php中文网

原创

如何在点击锚点链接后关闭下拉菜单而不刷新页面

本文详细介绍了如何在不刷新页面的情况下,通过javascript实现点击内部锚点链接时自动关闭导航下拉菜单并重置汉堡图标状态。教程涵盖了初始的htmlcssjavascript设置,并提供了针对锚点链接的事件监听解决方案,确保用户体验的流畅性。

在现代网页设计中,导航菜单通常采用下拉式或侧滑式,并通过“汉堡”图标进行切换。一个常见的用户体验问题是,当用户打开下拉菜单并点击其中的内部锚点链接(例如,#about-us)跳转到页面特定部分时,下拉菜单并不会自动关闭,汉堡图标也不会恢复到初始状态。这可能导致用户困惑,并影响页面的整体交互流畅性。本教程将指导您如何通过JavaScript解决这一问题,确保点击锚点链接后菜单能够优雅地关闭。

初始设置回顾

为了更好地理解解决方案,我们首先回顾一下典型的汉堡菜单和下拉菜单的HTML结构、CSS样式以及基本的JavaScript交互逻辑。

HTML 结构

一个典型的导航菜单可能包含以下结构:






Lorem Ipsum is simply dummy text...

About Us

Lorem Ipsum is simply dummy text...

这里,navbar--middle 是下拉菜单容器,hamburger 是汉堡图标。nav-contents 内部包含指向页面内部锚点的链接。

CSS 样式

CSS主要负责菜单的显示/隐藏、定位以及汉堡图标的动画效果:

知了zKnown
知了zKnown

知了zKnown:致力于信息降噪 / 阅读提效的个人知识助手。

下载
.navbar--middle {
    display: none; /* 默认隐藏 */
    position: fixed;
    background: #dedede;
    width: 100%;
    /* 其他样式 */
    z-index: 9999;
}

.hamburger {
    /* 汉堡图标样式 */
    display: inline-block;
    cursor: pointer;
    position: fixed;
    z-index: 9999;
    /* 其他样式 */
}

/* 汉堡图标动画效果 */
.change .icon1 {
    transform: rotate(-45deg) translate(-5px, 4px);
}
.change .icon2 {
    opacity: 0;
}
.change .icon3 {
    transform: rotate(45deg) translate(-6px, -5px);
}

关键在于 navbar--middle 默认 display: none;,并通过JavaScript来切换其显示状态。汉堡图标的 .change 类则控制其变为“关闭”图标的动画。

JavaScript 基础交互

最初的JavaScript代码通常只处理汉堡图标的点击事件,用于切换菜单的显示和汉堡图标的动画:

var hamburger = document.getElementById('hamburger');
var menu = document.getElementById('navbar--middle');

// 初始设置菜单为隐藏(如果CSS未设置)
// menu.style.display = "none"; 

hamburger.addEventListener('click', function() {
    this.classList.toggle("change"); // 切换汉堡图标动画
    if (menu.style.display === "none") {
        menu.style.display = "block"; // 显示菜单
    } else {
        menu.style.display = "none"; // 隐藏菜单
    }
});

这段代码能够实现点击汉堡图标时菜单的打开和关闭,以及汉堡图标的相应动画。然而,它并未考虑点击菜单内部的锚点链接时的行为。

解决方案:监听锚点链接点击事件

要解决上述问题,我们需要为下拉菜单内的所有锚点链接添加一个额外的事件监听器。当这些链接被点击时,除了执行默认的页面跳转行为外,我们还需要手动关闭菜单并重置汉堡图标。

核心JavaScript代码

// 获取汉堡图标和菜单元素
var hamburger = document.getElementById('hamburger');
var menu = document.getElementById('navbar--middle');

// 1. 汉堡图标点击事件:切换菜单显示/隐藏和汉堡图标动画
hamburger.addEventListener('click', function() {
  this.classList.toggle("change"); // 切换汉堡图标动画
  if (menu.style.display === "none") {
    menu.style.display = "block"; // 显示菜单
  } else {
    menu.style.display = "none"; // 隐藏菜单
  }
});

// 2. 锚点链接点击事件:关闭菜单并重置汉堡图标
var anchors = document.querySelectorAll('.nav-contents > a'); // 获取所有导航锚点链接

anchors.forEach(item => {
    item.addEventListener('click', () => {
        menu.style.display = "none"; // 隐藏菜单
        hamburger.classList.remove("change"); // 移除汉堡图标的"change"类,恢复其初始状态
    });
});

代码解析

  1. var anchors = document.querySelectorAll('.nav-contents > a');
  2. anchors.forEach(item => { ... });
    • querySelectorAll 返回的是一个 NodeList,它是一个类似数组的对象。我们使用 forEach 方法遍历这个 NodeList 中的每一个锚点链接元素。
  3. item.addEventListener('click', () => { ... });
    • 为每个锚点链接添加一个 click 事件监听器。当用户点击其中任何一个链接时,回调函数将被执行。
  4. menu.style.display = "none";
    • 在回调函数内部,我们首先将 menu 元素的 display 样式设置为 "none",从而隐藏下拉菜单。
  5. hamburger.classList.remove("change");
    • 接着,我们从 hamburger 元素中移除 change 类。这个类通常用于触发汉堡图标的动画,使其变为“X”形。移除它将使汉堡图标恢复到三条杠的初始状态,表示菜单已关闭。这里使用 remove 而不是 toggle 是为了确保无论汉堡图标当前是什么状态,都强制它回到关闭状态。

完整示例代码

为了方便理解,以下是整合了HTML、CSS和JavaScript的完整示例。

index.html




    
    
    Dropdown Menu with Anchor Link Close
    



    

    

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

关于我们

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

服务

This is the services section. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

联系我们

Contact us here. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

style.css

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding-top: 80px; /* 留出顶部导航空间 */
}

.main-nav {
    display: flex;
    flex-direction: row;
    width: 100%;
    margin: 0 auto;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10000; /* 确保导航在最上层 */
    background: white;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.main-nav .nav-contents {
    font-size: 20px; /* 调整字体大小 */
    padding: 20px 0;
}

.nav-contents a {
    display: block;
    padding: 10px 55px;
    text-decoration: none;
    color: #333;
    transition: background-color 0.3s ease;
}

.nav-contents a:hover {
    background-color: #f0f0f0;
}

.navbar--middle {
    display: none; /* 默认隐藏 */
    position: fixed;
    background: #dedede;
    width: 100%;
    padding: 20px 10px 20px 0px; /* 调整内边距 */
    height: 100%; /* 全屏高度 */
    top: 0;
    left: 0;
    z-index: 9999;
    overflow-y: auto; /* 允许内容滚动 */
}

.hamburger {
    display: inline-block;
    cursor: pointer;
    position: absolute; /* 相对于 .main-nav 定位 */
    z-index: 9999;
    background: white;
    padding: 10px;
    margin: 0;
    right: 20px; /* 调整右侧定位 */
    top: 10px; /* 调整顶部定位 */
    border-radius: 50%;
    border: 4px solid green;
}

.icon1, .icon2, .icon3 {
    width: 25px;
    height: 3px;
    background-color: orange;
    margin: 4px 0;
    border-radius: 5px;
    transition: 0.4s;
}

/* Rotate first bar */
.change .icon1 {
    -webkit-transform: rotate(-45deg) translate(-5px, 4px);
    transform: rotate(-45deg) translate(-5px, 4px);
}

/* Fade out the second bar */
.change .icon2 {
    opacity: 0;
}

/* Rotate last bar */
.change .icon3 {
    -webkit-transform: rotate(45deg) translate(-6px, -5px);
    transform: rotate(45deg) translate(-6px, -5px);
}

/* 响应式调整 */
@media (min-width: 768px) {
    .hamburger, .navbar--middle {
        display: none !important; /* 在大屏幕上隐藏汉堡和下拉菜单 */
    }
    .main-nav .nav-contents {
        display: flex; /* 在大屏幕上显示为水平导航 */
        width: auto;
        padding: 0;
        margin-left: auto; /* 将导航推到右侧 */
    }
    .nav-contents a {
        display: inline-block;
        padding: 20px 15px;
    }
}

script.js

document.addEventListener('DOMContentLoaded', function() {
    var hamburger = document.getElementById('hamburger');
    var menu = document.getElementById('navbar--middle');

    // 1. 汉堡图标点击事件:切换菜单显示/隐藏和汉堡图标动画
    if (hamburger && menu) { // 确保元素存在
        hamburger.addEventListener('click', function() {
            this.classList.toggle("change"); // 切换汉堡图标动画
            if (menu.style.display === "none" || menu.style.display === "") {
                menu.style.display = "block"; // 显示菜单
            } else {
                menu.style.display = "none"; // 隐藏菜单
            }
        });
    }

    // 2. 锚点链接点击事件:关闭菜单并重置汉堡图标
    var anchors = document.querySelectorAll('.nav-contents > a'); // 获取所有导航锚点链接

    anchors.forEach(item => {
        item.addEventListener('click', () => {
            if (menu.style.display === "block") { // 仅当菜单打开时才执行关闭操作
                menu.style.display = "none"; // 隐藏菜单
                if (hamburger) { // 确保汉堡图标存在
                    hamburger.classList.remove("change"); // 移除汉堡图标的"change"类,恢复其初始状态
                }
            }
        });
    });
});

注意事项与总结

  1. DOM内容加载: 确保您的JavaScript代码在DOM完全加载后执行。将脚本放在

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
php中foreach用法
php中foreach用法

本专题整合了php中foreach用法的相关介绍,阅读专题下面的文章了解更多详细教程。

75

2025.12.04

js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

514

2023.06.20

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

244

2023.07.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

298

2023.08.03

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

5306

2023.08.17

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

481

2023.09.01

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

212

2023.09.04

Js中concat和push的区别
Js中concat和push的区别

Js中concat和push的区别:1、concat用于将两个或多个数组合并成一个新数组,并返回这个新数组,而push用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度;2、concat不会修改原始数组,是创建新的数组,而push会修改原数组,将新元素添加到原数组的末尾等等。本专题为大家提供concat和push相关的文章、下载、课程内容,供大家免费下载体验。

218

2023.09.14

Golang 网络安全与加密实战
Golang 网络安全与加密实战

本专题系统讲解 Golang 在网络安全与加密技术中的应用,包括对称加密与非对称加密(AES、RSA)、哈希与数字签名、JWT身份认证、SSL/TLS 安全通信、常见网络攻击防范(如SQL注入、XSS、CSRF)及其防护措施。通过实战案例,帮助学习者掌握 如何使用 Go 语言保障网络通信的安全性,保护用户数据与隐私。

0

2026.01.29

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.8万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.1万人学习

CSS教程
CSS教程

共754课时 | 24.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号