简体   繁体   中英

Chrome ignoring hashes in URL

I've spent quite a while trying to find answers for this issue, but haven't had any success. Basically I need to scroll the user to the contact portion of the website when they go to healthdollars.com/#contact . This works just fine in Safari, but in Chrome I haven't had any luck. I've tried using jQuery/Javascript to force the browser to scroll down, but I haven't been able to.

Does anyone have any ideas? It's driving me crazy - especially since it's such a simple thing to do.

Not a full answer but in Chrome if you disable Javascript I believe you get the desired behavior. This makes me believe that something in your JavaScript is preventing default browser behavior.

It looks to me like the target element doesn't exist when when page first loads. I don't have any problem if I navigate to the page and then add the hash.

if (window.location.hash.length && $(location.hash)) {
  window.scrollTo(0, $(location.hash).offset().top)
}

check for a hash, find the element's page offset, and scroll there (x, y).

edit: I noticed that, in fact, the page starts at #contact, then scrolls back to the top. I agree with the other answerer that there's something on your page that's scrolling you to the top. I'd search for that before adding a hack.

You can do this with JS, for example` if you have JQuery.

$(function(){
  // get the selector to scroll (#contact)
  var $to = $(window.location.hash);

  // jquery animate
  $('html'/* or body */).animate({ scrollTop: $to.offset().top });
});

The name attribute doesn't exists in HTML 5 so chrome looks to have made the name attribute obsolete when you use the DOCTYPE html.

The other browsers have yet to catch up.

Change

<a name="contact"></a>

to

<a id="contact"></a>

Maybe this workaround with vanilla javascript can be useful:

// Get the HTMLElement that you want to scroll to. 
var element = document.querySelector('#contact');
// Stories the height of element in the page.
var elementHeight = element.scrollHeight;
// Get the HTMLElement that will fire the scroll on{event}.
var trigger = document.querySelector('[href="#contact"]');    
trigger.addEventListener('click', function (event) {
  // Hide the hash from URL.
  event.preventDefault();
  // Call the scrollTo(width, height) method of window, for example.
  window.scrollTo(0, elementHeight);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM