滚动后删除锚链接 - 也适用于其他页面的链接

时间:2015-12-31 17:39:17

标签: javascript jquery

我已经设置了一个平滑滚动的单页网站,在平滑滚动后从URL中剥离锚链接。这是我使用的jQuery:

$(function() {
    $('a.page-scroll').on('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top  - 60
        }, 1000, 'easeInOutExpo');
        event.preventDefault();
    });
});

在我添加其他页面之前,一切都很有效。我无法通过另一个外部网页上的<a class="page-scroll" href="../#contact">Contact</a>之类的链接删除锚点链接。

我已经在SO上搜索了高低,但无法找到有效的解决方案。

如果链接来自外部页面,我并不完全关心平滑滚动。我最需要的是导航/滚动到主页面的id部分(带偏移量以容纳固定导航),当链接来自外部页面时(从我网站上的其他页面),从浏览器URL窗口中删除锚点链接,或来自其他网站。)

我也试过这个,但它同样只适用于同一页面上id的内部链接:

<script>
$(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 - 60
        }, 1000);
        return false;
      }
    }
  });
});
</script>

我也试过这个没有运气:

    <script type="text/javascript">
(function($) {
    $(document).ready(function() {
    var url=document.URL.split("#");
    var ancher=url[1];
         $('html, body').animate({
           'scrollTop':   $('#'+ancher).offset().top - 60
         }, 5000);
    });
})(jQuery);
  </script>

任何新年前夕的帮助都会非常感激,所以我可以把这个项目结束!

1 个答案:

答案 0 :(得分:2)

我可能无法理解问题的严重程度,但我相信你正在尝试这样做,因此href不会在想要滚动的页面上触发,而是在链接到其他页面的页面上触发不是页面内的部分。也许这样的事情对你有用:

$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        if ($anchor[0].href[0] === '#') {
            $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top  - 60
            }, 1000, 'easeInOutExpo');
            event.preventDefault();
            return false;
        } else {
            return true;
        }
    });
});

这样做是为了看到href中的主角是#意味着它是指向其内部的链接。

如果有帮助和/或我是否走在正确的轨道上,请告诉我。

ps:我把.bind留在那里因为我不知道你在使用什么版本的jQuery,但是更新的语法是使用.on

新年快乐

只是稍微附加一下,使得主页的深层链接转到相应的部分,但没有哈希标记:

您可以从window.location中删除该'hash'变量,但如果您尝试完全删除该hashtag,则会导致浏览器刷新。这也会导致观众失去斑点(从而消除深层链接的目的)。

更改哈希标记值(保留#):

window.location.hash = ''; // clears the hash tag

删除哈希标记及其值(清除#及其后的所有内容):

window.location.href = window.location.href.substr(0, window.location.href.indexOf('#')); // this causes a browser refresh

如果它不完全明显,你会在页面加载

上运行它
$(document).ready(function() {
    if (typeof(window.location.hash) !== 'undefined' && window.location.hash.length > 0) {
        window.location.hash = ''; // will clear the hash anytime someone arrives with a hash tag
    }
});
相关问题