问题原文
原帖链接 · Josh Holly · CC BY-SA 4.0
So I have a one-page website with multiple sections and IDs. Right now, in the nav, I have it going to #about to jump them down to a section with ID=about
But I want the user to be able to go to mysite.com/#about but without the #. So if the user goes to mysite.com/about, it will jump them down to the about section on the same domain.
How can I accomplish this? I imagine it's a dot htaccess modification with some javascript?
I've Googled all over for a solution but to no avail.
社区高分解答
原帖链接 · MrWhite · CC BY-SA 4.0
Assuming the file that renders your "one-page" site is index.html and your "pages" are /about, /contact and /help that correspond to elements with ids of the same name (less the slash prefix).
Your root .htaccess code would be something like the following, using mod_rewrite:
RewriteEngine On
RewriteRule ^(about|contact|help)$ index.html [L]
The above rewrites requests for the 3 URLs stated to index.html. So, those 3 URLs get the same HTTP response.
Then, JavaScript on the page would be something like:
// Get the URL-path, less the slash prefix
const id = location.pathname.substring(1);
// Get the HTML "page" element whose ID is passed in the URL.
const element = document.getElementById(id);
if (element) {
element.scrollIntoView();
}
Note that the id could be empty or index.html. (Aside: You could redirect from /index.html to / in .htaccess.)
Although, as mentioned in comments, this might have accessibility issues over using the standard fragment identifier. And /#about and /about will return the same response - the first being handled by the browser and the second by JavaScript.
Reference:
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
