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

页面加载时如何通过锚点标签切换Div并显示指定定价选项

嘿,我来帮你搞定这个锚点切换定价选项的需求!下面是一套完整的实现方案,用HTML、CSS和JavaScript就能轻松实现你的要求:

锚点驱动的定价选项切换实现

1. HTML 结构

先搭建基础的导航锚点和定价选项容器,给每个定价模块设置唯一ID,方便后续定位:

<!-- 锚点导航栏 -->
<div class="pricing-nav">
  <a href="#Standard">Standard Pricing</a>
  <a href="#Club-Youth">Club and Youth Pricing</a>
</div>

<!-- 定价选项容器 -->
<div class="pricing-container">
  <div id="Standard" class="pricing-card active">
    <h3>Standard Pricing</h3>
    <p>$99 / 月</p>
    <ul>
      <li>全功能访问</li>
      <li>10GB存储空间</li>
    </ul>
  </div>
  <div id="Club-Youth" class="pricing-card">
    <h3>Club and Youth Pricing</h3>
    <p>$49 / 月</p>
    <ul>
      <li>核心功能访问</li>
      <li>5GB存储空间</li>
      <li>专属社群支持</li>
    </ul>
  </div>
</div>

2. CSS 样式

用CSS控制定价模块的显示/隐藏状态,默认只有带.active类的模块可见:

.pricing-card {
  display: none; /* 默认隐藏所有定价模块 */
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-top: 15px;
}

.pricing-card.active {
  display: block; /* 激活状态的模块显示 */
}

.pricing-nav a {
  margin-right: 18px;
  text-decoration: none;
  color: #333;
  font-weight: 500;
}

.pricing-nav a:hover {
  color: #0066cc;
  border-bottom: 2px solid #0066cc;
}

3. JavaScript 核心逻辑

实现页面加载时的锚点检测,以及锚点变化时的自动切换:

// 定义通用的切换函数
function togglePricing(targetId) {
  // 先移除所有模块的激活类
  document.querySelectorAll('.pricing-card').forEach(card => {
    card.classList.remove('active');
  });
  // 给目标模块添加激活类
  const targetCard = document.getElementById(targetId);
  if (targetCard) {
    targetCard.classList.add('active');
  }
}

// 页面加载完成后检查锚点
document.addEventListener('DOMContentLoaded', () => {
  const currentHash = window.location.hash.slice(1); // 去掉锚点的#号
  // 如果锚点是Club-Youth则切换到对应模块,否则默认显示Standard
  if (currentHash === 'Club-Youth') {
    togglePricing('Club-Youth');
  } else {
    togglePricing('Standard');
  }
});

// 监听锚点变化事件(比如用户点击导航链接)
window.addEventListener('hashchange', () => {
  const currentHash = window.location.hash.slice(1);
  togglePricing(currentHash);
});

功能说明

  • 页面加载时会自动识别URL锚点:如果URL末尾是#Club-Youth,直接显示“Club and Youth”定价模块;否则默认展示第一个“Standard”模块。
  • 点击导航栏的锚点链接时,页面会自动切换到对应的定价模块,同时URL锚点也会同步更新。
  • 代码扩展性强,后续新增定价选项时,只需要添加对应的HTML模块和锚点链接即可,无需修改JS逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:53:47