如何创建页内锚点链接(href="#..." / PHP & Bootstrap环境)
Hey there! Let's work through why your anchor links aren't playing nice with your PHP routing setup. Since every page is handled through index.php (using URL params like ?page=xxx), the issue is almost certainly that your plain href="#idName" links are losing the current page context when clicked. Here's how to fix it:
1. First, confirm your target anchor exists (and is unique)
Make sure the element you want to jump to has a unique id attribute in the content being rendered for the current page. For example:
<div id="pricing-block" class="container mt-4"> <!-- Your pricing content goes here --> </div>
No duplicate IDs on the page either—browsers will only jump to the first matching element, so duplicates break the functionality.
2. Keep your routing context in the anchor link
When you click a link like href="#pricing-block", the browser will navigate to index.php#pricing-block instead of index.php?page=your-current-page#pricing-block. That means it loads your site's default page (not the one you're on) and tries to find the anchor there—hence no jump happens.
To fix this, dynamically append the current query string to your anchor link using PHP:
<?php // Grab the current query string (e.g., "page=services") $current_query = $_SERVER['QUERY_STRING']; // Build the full anchor URL $anchor_link = $current_query ? "?$current_query#pricing-block" : "#pricing-block"; ?> <a href="<?php echo $anchor_link; ?>" class="text-decoration-none">Jump to Pricing</a>
This way, clicking the link takes you to index.php?page=services#pricing-block, so the correct page loads and the browser can find the anchor.
3. Double-check your dynamic content is loaded
Make sure the section with the anchor ID is actually being rendered when the current page parameter is set. For example, if you're using conditionals like:
if ($_GET['page'] === 'services') { include 'services-content.php'; // This file must contain your #pricing-block element }
Verify that the included file has the correct ID—if it's missing, the anchor has nothing to jump to.
Since you're using Bootstrap without JavaScript, none of the framework's components should interfere with basic anchor behavior—this is all about preserving your PHP routing context in the link.
内容的提问来源于stack exchange,提问作者user9421174

