【问题标题】:Remove the anchor in the URL删除 URL 中的锚点
【发布时间】:2015-03-09 03:30:49
【问题描述】:

我的 jQuery 有问题,我有一个包含多个锚点的网站,我使用平滑滚动转到锚点。问题是我在 URL 中有锚点。

这是我的代码:

/**
 * Checks if anchor exists. If it exists, scroll to it
 */
function scroll_if_anchor(href) {
    href = typeof(href) == "string" ? href : $(this).attr("href");

    // dynamically caluclates height
    var fromTop;
    var speed = 750; // Durée de l'animation (en ms)
    var headerHeight = $('#header').height(),
        navHeight = $('.nav-secondaire').height();

    if( headerHeight + navHeight > 200){
        fromTop = 300;
    } else {
        fromTop = 120;
    }

    // If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
    // Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
    if(href.indexOf("#") == 0) {
        var $target = $(href);

        // Older browser without pushState might flicker here, as they momentarily
        // jump to the wrong position (IE < 10)
        if($target.length) {
            $('html, body').animate({ scrollTop: $target.offset().top - fromTop }, speed);
            if(history && "pushState" in history) {
                history.pushState({}, document.title, window.location.pathname + href);
                return false;
            }
        }
    }
}    

// When page loads, scroll to anchors
scroll_if_anchor(window.location.hash);

// Intercept all clicks on anchors
$("body").on("click", "a", scroll_if_anchor); 

你有什么想法吗?

非常感谢!

【问题讨论】:

  • 我不明白问题出在哪里。页面没有滚动到所需位置吗?
  • Do you have an idea 不是正确的问题陈述 请解释您遇到的问题。

标签: javascript jquery


【解决方案1】:

您发布的代码可以平滑滚动页面上的链接,当您访问页面时滚动到特定锚点,将以下代码添加到您的 javascript 末尾。确保在加载整页时调用它。

var url = window.location.hash;
url = url.substring(url.indexOf('#'));
scroll_if_anchor(url)

【讨论】:

    【解决方案2】:

    location.hash 可能不包含初始井号,因此在将其传递给您的函数之前,您必须确保它存在(期望井号存在):

    scroll_if_anchor(location.hash.replace(/^([^#])/, '#$1'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 2011-02-22
      • 1970-01-01
      • 2021-05-24
      • 2019-03-13
      • 2013-12-05
      相关资源
      最近更新 更多