Jquery scroll to offset target div on page load

后端 未结 2 422
感动是毒
感动是毒 2021-01-07 10:20

I\'m trying to scroll to the div that is in the URL. It could be one of 21 IDs like:

url.com/test#lite1

url.com/test#lite2

url.com/test#lite3

相关标签:
2条回答
  • 2021-01-07 11:01

    window.location.hash contains the current hash in the URL so use that. As the hash is already in the URL(as you said that they come to page by clicking on link with hash) so you don't need to add it manually. Try using this :

    $(document).ready(function(){
         $('html,body').animate({
              scrollTop: $(window.location.hash).offset().top-150
          }, 900, 'swing');
    });
    

    Using wordpress, it seems the $ needs to be replaced by jQuery so it comes out to:

    jQuery(document).ready(function(){
         jQuery('html,body').animate({
              scrollTop: jQuery(window.location.hash).offset().top-150
          }, 900, 'swing');
    });
    
    0 讨论(0)
  • 2021-01-07 11:01

    As an alternative, you could try using the following jQuery plugins. I've used them on multiple projects. They're customizable and provide nice, smooth animation:

    scrollTo (download, documentation) allows you to scroll to a specific element on the page. Basic usage: $(element).scrollTo(target);

    localScroll (download, documentation) requires scrollTo as a dependency, and handles anchors for you. You can apply it to specific set of links by selecting their container: $('#link-container').localScroll();, or you can activate it globally: $.localScroll();

    0 讨论(0)
提交回复
热议问题