jQuery滚动到锚点返回NaN作为位置哈希

时间:2017-01-31 14:04:23

标签: javascript jquery html css scroll

我正在使用以下jQuery代码实现动画滚动到锚点:

(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 - 150
        }, 1500, 'swing', function()
        {
            location.hash = target - 150;
        });
};
$('html, body').hide();
$(document).ready(function()
{
    $('a[href^=#]:not(#toggle)').on("click", jump);
    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump()
        }, 0);
    }else{
        $('html, body').show()
    }
});
})(jQuery);

从上面的代码中可以看出,我使用的目标偏移值为150px:

scrollTop: $(target).offset().top - 150

为了使这段代码正常工作,我还需要将带有offset的目标传递给location.hash。这就是我这样做的方式:

location.hash = target - 150;

在这种实现下,代码工作正常。除非它在滚动到锚点时始终在URL中显示#NaN。这显然是因为上面这一行。但是,如果我不使用-150px,那么它会使用偏移滚动到目标,然后突然跳转到原始锚位置而不会偏移。

我的问题是,我如何才能实现双赢局面?我的意思是,URL中没有#NaN,并且正确地滚动到从顶部偏移的锚点。我听说可以使用" e.preventdefault",但不知何故它对我不起作用。

非常感谢任何建议。

2 个答案:

答案 0 :(得分:0)

尝试

$('html,body').animate(
    {
        scrollTop: $(target).offset().top - 150
    }, 1500, 'swing');
location.hash = target;
};

我有同样的问题,现在可行了

答案 1 :(得分:0)

select * FROM "_SYS_BIC"."FinancialReporting.ReportingViews.Tech_Analytics/CV_LOA_FINANCIAL_DETAIL_GRA" F1 JOIN "_SYS_BIC"."FinancialReporting.MasterData/CV_D_ACCOUNT_GRA" F2 ON F1."acct_nmbr" = F2."acct_nmbr" JOIN "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COMPANY_GRA" F3 ON F1."company_cd" = F3."company_cd" JOIN "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COSTCENTER_GRA" F4 ON F1."cost_center_cd" = F4."cost_center_cd" JOIN "_SYS_BIC"."FinancialReporting.ReportingViews/CV_LOA_MEASURES_LEVELS_TA_GRA" F5 ON F1."acct_nmbr" = F5."acct_nmbr" LEFT JOIN "_SYS_BIC"."FinancialReporting.MasterData/CV_D_VENDOR_GRA" F6 ON F1."vendor_cd" = F6."vendor_cd" WHERE F1."acctg_dt" >= '2016-01-01' AND F1."acctg_dt" <= '2016-02-01'; 包含#,因此如果您尝试对其进行算术运算,则无法将其转换为数字。

请改用location.hash。每当您尝试将该数字用作DOM ID时,您都需要添加#。

(您可能会考虑将代码更改为不使用相同的变量来指示DOM节点和滚动位置;但它相当令人困惑。如果我重构这个,我会将这些ID更改为有意义的标签,并根据这些元素Number(location.hash.substr(1))而不是散列本身的数字内容设置滚动位置。)