jQuery滚动到锚点,从外部页面偏移

时间:2015-08-25 22:01:57

标签: javascript jquery

我在页面上有一些锚点。要从页面本身导航到它们,我使用的是基本的jQuery函数,主要是偏移量:

jQuery(document).ready(function(){
jQuery('a[href^="http://website.org/visit-us#anchor1"]').on('click',function (e) { 

e.preventDefault();
var target = this.hash; 
var $target = jQuery(target); 
jQuery('html, body').stop().animate({
'scrollTop': $target.offset().top - 250},#
900, 
'swing',function () {
window.location.hash = target - 240 ;
});

});
});

问题是当我使用其他页面的链接时,如果代码被加载,它不会重定向到链接。如果未加载代码,则会传递锚链接。

如何修改函数以将其加载到其他页面上以使偏移量有效?

1 个答案:

答案 0 :(得分:6)

在这种情况下,触发类似你已经写过的函数应该可以工作:

jQuery(document).ready(function(){

// run on DOM ready

// grab target from URL hash (i.e. www.mysite.com/page-a.html#target-name)
var target = window.location.hash;

// only try to scroll to offset if target has been set in location hash
if ( target != '' ){
    var $target = jQuery(target); 
    jQuery('html, body').stop().animate({
    'scrollTop': $target.offset().top - 250},
    900, 
    'swing',function () {
    window.location.hash = target - 240 ;
    });
}

});

然后在第B页:

<a href="page-a.html#target-name">Link to #target-name on page A</A>