不同标题类型间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:
1. Verify Your Navigation Link Structure
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
hrefandidmatch exactly (e.g.,#SampleTitlevs#sample-titleare treated as different targets). - Duplicate IDs: Make sure no other element on the page uses the same
idas 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 callingevent.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

