0

我目前在我的wordpress页面上使用“平滑滚动”,并且我试图让页面在来自外部链接时平滑滚动到请求的部分(使用锚点(#portfolio)从那里开始我希望页面从顶部然后滚动到投资组合部分。

发生的事情是它短暂地显示“投资组合部分”(锚点跳转),然后重置到顶部并向下滚动。

代码

$(function() {
    $('.menu li a').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) {
        $root.animate({
        scrollTop: target.offset().top - 75
        }, 800, 'swing');
            return false;  
            }
        }
    });
});

页面加载

$(window).on("load", function() {
if (location.hash) { // do the test straight away
    window.scrollTo(0, 0); // execute it straight away
    setTimeout(function() {
    window.scrollTo(0, 0); // run it a bit later also for browser compatibility
    }, 1);
}
var urlHash = window.location.href.split("#")[1];
if (urlHash && $('#' + urlHash).length)
    $('html,body').animate({
    scrollTop: $('#' + urlHash).offset().top - 75
    }, 800, 'swing');
});

如何防止页面加载时似乎发生的“跳跃”?

HTML - 导航链接(使用虚拟链接)

<a href="link.com/#portfolio>portfolio</a>

HTML - div

<div id="portfolio></div>
4

1 回答 1

0

您可以通过更改锚点来规避浏览器行为,以便它携带一些页面访问独有的附加文本。在下面的示例中,我将前六行添加到您的函数中以设置 AnchorSeed 变量,然后在您分配 urlHash 变量的位置使用该变量:

$(window).on("load", function() {
    var AnchorSeed = new Date() * 1;
    $( ".AnchorUpdate" ).each(
        function() {
            $( this ).attr( "id", this.id + AnchorSeed );
        }
    );
    if (location.hash) { // do the test straight away
        window.scrollTo(0, 0); // execute it straight away
        setTimeout(function() {
            window.scrollTo(0, 0); // run it a bit later also for browser compatibility
        }, 1);
    }
    var urlHash = window.location.href.split("#")[1] + AnchorSeed;
    if (urlHash && $('#' + urlHash).length)
        $('html,body').animate({
        scrollTop: $('#' + urlHash).offset().top - 75
        }, 800, 'swing');
});

您需要将 AnchorUpdate 类添加到您可能跳转到的任何页面元素,以便 jQuery 例程可以找到它并使用 AnchorSeed 值更新其 id。在这种情况下,我们知道“portfolio”就是这样一个链接,所以它会被修改为:

<div class="AnchorUpdate" id="portfolio></div>

这样做的效果是 id 将从“portfolio”更改为“portfolio1382124849780”(当然,取决于页面加载时的时间戳)。

因为当页面完成加载时id“portfolio”将不存在(即使它是源HTML的一部分),浏览器不应该反弹到它。

我完全使用 JavaScript,因为我不知道您是否可以访问服务器变量。如果你这样做,我认为它们可能是一个更可取的解决方案,因为代码将更具可读性。如果可能,您可能会使用页面计数器变量,或者只是使用服务器端时间戳。

编辑:

在您提到的评论中,这适用于外部链接,但它破坏了内部链接。我现在没有时间设置测试,但我认为添加一个 jQuery 例程来更新类似于上面所做的那些内部链接是可行的。例如,您的内部链接是:

<a href="#InternalLink">Jump to Internal Link</a>

你可以给它一个不同的类来表明它需要更新:

<a class="InternalLinkUpdate" href="#InternalLink">Jump to Internal Link</a>

然后使用 jQuery 触发对该类的类似修改:

$( ".InternalLinkUpdate" ).each(
    function() {
        $( this ).attr( "href", $( this ).attr( "href" ) + AnchorSeed );
    }
);

(由于我目前无法从工作代码中复制,我可能在上面犯了标点错误或类似的错误——但它不应该花太多的时间来让它正常工作。

于 2013-10-18T19:38:50.773 回答