是否可以通过jQuery.load()加载外部元素后滚动到锚点

Is it possible to scroll to anchor after external elements are loaded through jQuery.load()?

本文关键字:元素 滚动 外部 加载 jQuery 可以通过 load 是否      更新时间:2023-09-26

场景是这样的:

  • 从RSS源链接到我的网站http://website.com/#anchorelement
  • 我想跳转/滚动到#anchorelement

http://website.com/准备好后,jQuery.load() 加载#anchorelement。因此,使用链接http://website.com/#anchorelement不会跳转到#anchorelement,因为在执行跳转时还没有加载元素。

谁有什么建议,如何使这个工作?是否有可能用javascript拦截锚跳并使其等待直到jQuery.load()调用完成?

谢谢!

$(function(){
  // so this is inside your document ready function.
  // you need to add a callback
  $( somecontainer ).load('somecontent', function(){
    // after the content has been loaded
    // check if a hash is present in the location
    if( window.location.hash != '' ){ 
      // find an element with matching id
      var anchor = $( location.hash ).get(0);
      // if element was found scroll it into view
      if( anchor ){ anchor.scrollIntoView() }
    }
  });
});

如果你有多个内容要加载,使用回调函数逐个加载,如果你想在其中一个上滚动,在最后一个回调时调用函数scroll。

$(function ()
{
  //Get the hash and load your content
  var hash = location.hash.replace('#', '');
  loadLocationContent(hash);
});
function loadLocationContent(hash)
{
  $('container1').load("someContent1", function(){
    $('container2').load("someContent2", function(){
      $('container3').load("someContent3", function(){
        $('container4').load("someContent4", scrollToHashAfterContentLoad(hash));
      });
    });  
  });
}
function scrollToHashAfterContentLoad(hash, contentId)
{
  if (hash != '')
  {
    $('html, body').animate({ scrollTop: $('#' + hash).offset().top }, 2000);
  }
}