PHP Header Location - Move to anchor without reloa

2019-07-26 09:16发布

问题:

I'm trying to come up with a way to navigate to HTML anchors within the same page without reloading. Right now I'm just using:

header("Location: #anchor_name");

The problem with that is it reloads the page. I'd really like to avoid using JavaScript if I can but I don't know if there's any other way?

Thank you!

PS - I know I need to use the full URI in the redirect - just abbreviated here for simplicity.

回答1:

You could use js:

 function scrollToAnchor_name(anchorName) {
     location.hash = "#" + anchorName;
 }


回答2:

In html, use <a href="#anchor_name">Click me</a>



回答3:

PHP is a server-side technology. Any change which has to be made to the page, either in terms of content or to determine which part is visible, can therefore only be achieved by addressing the server again. In and of itself (meaning: without the aid of client-side scripting such as ajax calls), this will always force a reload of the page. The only way to do this without a reload is by using client-side scripting, and then JavaScript is necessary (as described in the other posts on this page).



回答4:

If you have jQuery included in your site, here is some smooth code that I often use for that purpose:

function goToByScroll(id){
  $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}


回答5:

You could make the href to the page include the anchor, like "submit.php#form_top", and output that anchor or not with PHP depending on the submission. So when the page is first accessed, there will be no form_top anchor and it will just display from the top of the page, but for subsequent calls (posting forms), it will jump to the anchor.

The disadvantage would be the ugly URL with the always visible anchor, and it won't work if you call the url without the anchor (the anchor needs to be placed and remain for subsequent calls when it's needed).