Scroll to hash without nameAsk Question

问题:

I try to scroll to a unnamed hash e.g. comment section but no luck

$(document).ready(function () {
  console.log('ANC: ' + location.hash);

  setTimeout(function() {
    $('html,body').animate({
      scrollTop: window.location.hash.offset().top
    }, 'slow');
  }, 200);
});

Opening the link

http://example.com/foo/bar.html#1234567890

does not work with scrolling. I always get

Uncaught TypeError: window.location.hash.offset is not a function

location.href=location.hash;

works just great but no scrolling which is too bad.

Any advice?

回答1:


hash is just a string. Elements can have offsets, strings don't.

Try:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
}, 'slow');
标签: jquery dom scroll
© 2014 TuiCode, Inc.