jQuery scroll to ID on page A from page B (node, ejs)

半腔热情 提交于 2019-12-25 16:08:56

问题


this is my navbar

  <ul id="jump" class="dropdown-menu" role="menu">
      <li><a href="/main_page#top_something">People</a></li>
      <li><a href="/main_page">Main Page</a></li>
  </ul>

and I am using this function

(function($){

var jump=function(e)
{
   if (e){
       e.preventDefault();
       var target = $(this).attr("href");
   }else{
       var target = location.hash;
   }

   $('html,body').animate(
   {
       scrollTop: $(target).offset().top
   },1000,function()
   {
       location.hash = target;
   });

}

$('html, body').hide()

$(document).ready(function()
{
    $('#jump a[href]').bind("click", jump);

    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show()
            jump()
        }, 0);
    }else{
      $('html, body').show()
    }
});

})(jQuery)

main_page is a ejs file , and on /main_page route, node.js will render main_page.ejs file.

I am trying to click on navbar on A page and go to B page on div section. This give me : jump.js:18 Uncaught TypeError: Cannot read property 'top' of undefined error

Here is the same topic , jQuery scroll to ID from different page but I can't get it work ...thanks

Difference is that I have node.js and *.ejs files


回答1:


(function (){
  if(location.hash === '#top_something'){
      window.setTimeout(
        function(){ 
            $('html, body').animate({
            scrollTop: $('#top_something').offset().top
            }, 'slow');
        },2000);
  }
})();

This is what worked for me in this case :)



来源:https://stackoverflow.com/questions/39884440/jquery-scroll-to-id-on-page-a-from-page-b-node-ejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!