从子页面导航到主页并滚动到 id 的方法

Method for navigating from subpages to main page and scroll to id

本文关键字:滚动 id 方法 主页 导航      更新时间:2023-09-26

我不太擅长编码,所以我决定在这里问。也许任何人都可以为我所拥有的提供解决方案。

问题 - 我的主页上有 1 个导航链接,使用 jQuery 滚动到 id。它有效和一切,但仅在主页上。所有子页面在导航时都有此链接,我想问一下,当在每个不是主页的页面上单击链接时,如何将其导航回主页,然后执行滚动而不是子页面上什么都没有发生?谢谢。

这可能会

对你有所帮助

jQuery(function() {
    //catch all clicks on a tags
    jQuery("a").click(function(e){
        //check if it has a hash
        if(this.hash){
            var hash = this.hash.substr(1);
            var $toElement = jQuery("[id="+hash+"]");
            var width=jQuery(window).width();
            var toPosition = $toElement.offset().top;
        //scroll to element
            jQuery("body,html").animate({
                scrollTop : toPosition
            },2000);
            // return false;
            e.preventDefault();
        }
    });
    //do the same with urls with hash too
    if(location.hash){
        var hash = location.hash;
        jQuery("a[href="+hash+"]").click();
    }
});