同目录下从overview.php跳转至index.php锚点#landing失败求助
Hey Kasper, let's work through that anchor jump issue you're facing! I’ve dealt with similar problems when using PHP includes for content and navigation, so here’s a step-by-step breakdown of what to check and fix:
1. Verify the Anchor Element Exists in Rendered HTML
First things first: make sure the #landing anchor is actually present in the final HTML output of index.php. Since the div is included via PHP, sometimes path errors or missing includes can prevent it from loading.
- Open
index.phpin your browser, right-click, and select "View Page Source". - Search for
id="landing"— if you can’t find it, double-check your PHP include statement inindex.phpto ensure the file with the div is being correctly pulled in (e.g.,<?php include('path/to/your/landing-div-file.php'); ?>).
2. Fix Typos in Attributes
I noticed a couple of spelling mistakes in your code that might be causing unexpected behavior:
- The div has
data-ancor="landing"— that should bedata-anchor="landing"(correct spelling of "anchor"). - Your navigation link has
data-taget="#landing"— change that todata-target="#landing".
While these typos might not break the native anchor jump directly, they can interfere with any JavaScript that might rely on these attributes, so fixing them is a good first step.
3. Add JavaScript to Force Anchor Positioning
Sometimes browsers don’t properly detect anchors that are loaded via server-side includes on page load. Adding a small script to index.php can force the browser to scroll to the anchor once the page is fully loaded:
window.addEventListener('load', function() { const targetHash = window.location.hash; if (targetHash) { const anchorElement = document.querySelector(targetHash); if (anchorElement) { anchorElement.scrollIntoView({ behavior: 'smooth', // Optional: adds smooth scrolling block: 'start' }); } } });
This script checks the URL for a hash when the page finishes loading, finds the corresponding element, and scrolls directly to it.
4. Check for CSS Conflicts
CSS overflow settings can sometimes block native anchor scrolling. If a parent container of the #landing div has overflow: hidden or overflow: scroll, the browser might scroll that container instead of the entire page.
- Inspect the
#landingdiv and its parent elements using your browser’s dev tools (F12). - Ensure the
<body>and<html>elements don’t haveoverflow: hiddenset, and that their height is set toautoor100%to allow full-page scrolling.
5. Test a Simplified Link
Temporarily remove the custom data-target attribute from your navigation link to rule out conflicts with any JavaScript plugins you might be using:
<li><a href="index.php#landing">Forside</a></li>
Test this simplified link — if it works, the issue was likely related to the custom attribute interfering with your site’s JS.
Start with these steps, and you should have that anchor jump working in no time!
内容的提问来源于stack exchange,提问作者Kasper

