jQuery scrollTop无法使用查询字符串链接

use*_*331 8 jquery

我有一个导航,初始网址如下所示:

test.php?query=19

我的页面上有链接 <a href="#section-1">Section 1</a><a href="#section-2">Section 2</a><a href="#section-3">Section 3</a>

有3个部分:

<section id="section-1"></section><section id="section-2"></section><section id="section-3"></section>
Run Code Online (Sandbox Code Playgroud)

我正在使用此jquery代码从页面顶部(或用户在页面上的位置)滚动到该部分到该部分的顶部,而不是#在我的网址中显示标记.

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 2000);
                return false;
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,这不会滚动到该部分.它只是转到该部分的底部,然后滚动到顶部,并#显示在我的网址中.

我的主页上有另一个菜单:

home.php 我使用完全相同的jquery代码,它适用于该页面.

我的问题是如何让ScrollTop在我的test.php?query=19页面中工作就像home.php在我点击test.php?query=19我的网址上的内容时更改为:test.php?query=19#section-1

via*_*nes 1

我会改变你处理代码的逻辑。防止默认事件并通过attr直接访问href。

像这样的东西:

$(function() {
    $('a[href*=#]:not([href=#])').on('click', function(e) {
        e.preventDefault();
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var $target = $(this).attr('href');
            if ($target.size()) {
                $('html,body').animate({
                    scrollTop: $target.offset().top
                }, 2000);
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我不确定是否理解您正在使用的选择器a[href*=#]:not([href=#])。另外,条件(if location.pathnae.blah...)似乎相当尴尬。我会简单地做这样的事情:

$(function() {
    $('#some-wrapper').on('click', 'a.scroll-to', function(e) {
        e.preventDefault();
        var $target = $(this).attr('href');
        if ($target.size()) {
            $('html,body').animate({
                scrollTop: $target.offset().top
            }, 2000);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)