You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用HTML/CSS实现单页点击切换显示内容的菜单?

纯HTML/CSS实现点击按钮切换显示内容

你之前用:active伪类失败,是因为:active仅在元素被按住点击的瞬间生效,松开鼠标后就会失效,没法保持内容的显示状态。正确的方案是用CSS的:target伪类,它会匹配当前URL锚点指向的元素,正好适合这种点击锚点切换内容的场景。

完整实现代码

<!DOCTYPE html>
<html>
<head>
    <style>
        /* 默认隐藏所有内容板块 */
        .content-section {
            display: none;
            padding: 1rem;
            border: 1px solid #eee;
            margin-top: 1rem;
        }
        /* 匹配当前锚点指向的板块,设置为显示 */
        .content-section:target {
            display: block;
        }
        /* 按钮样式优化(可选) */
        .nav-btn {
            padding: 0.5rem 1rem;
            text-decoration: none;
            background: #f0f0f0;
            margin-right: 0.5rem;
            border-radius: 4px;
            color: #333;
        }
        .nav-btn:hover {
            background: #e0e0e0;
        }
    </style>
</head>
<body>
    <!-- 导航按钮 -->
    <a href="#home" class="nav-btn">首页</a>
    <a href="#about" class="nav-btn">关于</a>
    <a href="#contact" class="nav-btn">联系我们</a>

    <!-- 内容板块 -->
    <div id="home" class="content-section">
        <h2>首页内容</h2>
        <p>这是首页的默认展示内容,点击其他按钮可切换板块。</p>
    </div>
    <div id="about" class="content-section">
        <h2>关于我们</h2>
        <p>我们是一个专注于前端技术的小团队,用简单的技术实现实用的功能。</p>
    </div>
    <div id="contact" class="content-section">
        <h2>联系我们</h2>
        <p>邮箱:contact@example.com | 电话:123-4567890</p>
    </div>
</body>
</html>

核心逻辑说明

  • 所有内容板块默认通过display: none隐藏。
  • 点击锚点链接(比如href="#about")时,URL的锚点会变为#about,此时:target伪类会精准匹配id="about"的元素,将其display设为block来显示内容。
  • 切换其他按钮时,新的锚点会触发对应板块的:target状态,之前的板块因为不再是锚点目标,会自动恢复隐藏状态。

可选优化

如果需要页面加载时默认显示某个板块(比如首页),可以给该板块单独设置初始显示样式:

#home {
    display: block;
}

内容的提问来源于stack exchange,提问作者Chell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:16:03