2015-10-13 60 views
2

的情况是这样的:从一个RSS feed在通过jQuery.load()加载外部元素后,可以滚动到锚点吗?

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

然而,#anchorelement使用jQuery.load()后装http://website.com/已准备就绪。因此,使用链接http://website.com/#anchorelement不会跳转到#anchorelement,因为该元素在执行跳转时尚未加载。

有没有人有关于如何使这项工作的任何建议?是否有可能拦截与JavaScript的锚跳,并让它等到jQuery.load()呼叫完成?

谢谢!

+0

是的,你可以传递一个回调函数作为第二个参数给'jQuery.load',它会在完成后执行。编辑:你可能需要在回调中检查'window.location.hash',找到匹配的元素并使用'element.scrollIntoView()'滚动, – pawel

+0

谢谢!如果我的理解正确,那么发生的事情是,.load()之后的回调将从URL中获取.hash并在完成后滚动到它。 – jaka

回答

2
$(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() } 
    } 
    }); 
}); 
0

如果你有多个内容加载,加载它每一个使用回调函数之一,如果你想在其中一人,通话功能上的最后一个回调滚动滚动。

$(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); 
    } 
} 
相关问题