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

不同标题类型间Anchor tag行为不一致问题求助

First, let's break down why your "Sample Title" and "Sample Title 2" links aren't working—this almost always boils down to mismatched or missing anchor targets. Here's how to fix it step by step:

Make sure your sample title links use the correct href attribute pointing to the target section's unique id. For example:

<!-- Navigation Links -->
<a href="#sample-title">Sample Title</a>
<a href="#sample-title-2">Sample Title 2</a>

2. Add Matching IDs to Target Sections

Each section you want to jump to needs an id that exactly matches the href value (without the leading #). Like this:

<!-- Target Section for Sample Title -->
<section id="sample-title">
  <h2>Sample Title</h2>
  <!-- Your section content here -->
</section>

<!-- Target Section for Sample Title 2 -->
<section id="sample-title-2">
  <h2>Sample Title 2</h2>
  <!-- Your section content here -->
</section>

3. Check for Common Mistakes

  • Case Sensitivity: Ensure the href and id match exactly (e.g., #SampleTitle vs #sample-title are treated as different targets).
  • Duplicate IDs: Make sure no other element on the page uses the same id as your target sections—duplicates break anchor link functionality.
  • JavaScript Interference: Your provided myFunction() handles responsive nav toggling, but double-check if any other scripts are preventing default link behavior. If you have click event listeners on the links, avoid calling event.preventDefault() unless absolutely necessary.

Example Working Code Snippet

Here's a complete example tying everything together:

<!-- Responsive Navigation Bar -->
<div class="topnav" id="myTopnav">
  <a href="#home">Home</a>
  <a href="#about">About</a>
  <a href="#sample-title">Sample Title</a>
  <a href="#sample-title-2">Sample Title 2</a>
  <a href="javascript:void(0);" class="icon" onclick="myFunction()">
    <i class="fa fa-bars"></i>
  </a>
</div>

<!-- Target Content Sections -->
<section id="home">
  <h1>Home Section</h1>
</section>
<section id="about">
  <h1>About Section</h1>
</section>
<section id="sample-title">
  <h1>Sample Title Section</h1>
</section>
<section id="sample-title-2">
  <h1>Sample Title 2 Section</h1>
</section>

<!-- Your Existing Responsive Nav Script -->
<script>
function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
</script>

Quick Note

If you're using a frontend framework (like React, Vue, etc.), anchor links might need special handling (e.g., framework-specific routing tools), but based on your vanilla JavaScript snippet, the steps above should resolve the issue.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:05:47