如何禁用锚点“跳跃”加载页面时?

发布于 2024-09-18 13:26:14 字数 1134 浏览 5 评论 0原文

我认为这可能是不可能的,我会尽力解释。 我有一个包含选项卡(jquery 支持)的页面,由以下内容控制:

我正在使用此代码,由上一个问题中的另一个用户提供。

<script type="text/javascript">
    $(function() {

     $('html, body').animate({scrollTop:0}); // this is my "fix"

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;
     tabContent.not(hash).hide();
        if(hash=="") {
      $('#tab1').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href");

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

当我直接访问“选项卡”页面时,这段代码效果很好。

但是,我需要链接到其他页面的单独选项卡 - 为此,代码获取 window.location.hash 然后显示适当的选项卡。

由于“返回 false”,页面不会“跳转”到锚点。

然而,此事件仅在单击事件时触发。因此,如果我从任何其他页面访问我的“选项卡”,就会触发“跳转”效果。为了解决这个问题,我自动滚动到页面顶部,但我宁愿这没有发生。

有没有办法在页面加载时模拟“return false”,防止锚点“跳转”发生。

希望这足够清楚。

谢谢

I think this may not be possible, will try and explain as best as I can.
I have a page containing tabs (jquery powered), controlled by the following:

I'm using this code, as provided by another user from a previous question.

<script type="text/javascript">
    $(function() {

     $('html, body').animate({scrollTop:0}); // this is my "fix"

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;
     tabContent.not(hash).hide();
        if(hash=="") {
      $('#tab1').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href");

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

this code works great when I visit the "tabs" page directly.

however, I need to link to invidual tabs from other pages - so to do this, the code gets the window.location.hash then shows the appropiate tab.

the page doesn't "jump" to the anchor because of "return false".

this event is only triggered on a click event however. hence, if i visit my "tabs" from any other page, the "jump" effect is triggered. To combat this I automatically scroll to teh top of the page, but I would rather this didn't happen.

is there any way to simulate "return false" when the page loads, preventing the anchor "jump" from occuring.

hope this is clear enough.

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

归属感 2024-09-25 13:26:14

你的修复不起作用吗?我不确定我是否正确理解了这个问题 - 你们有演示页面吗?您可以尝试:

if (location.hash) {
  setTimeout(function() {

    window.scrollTo(0, 0);
  }, 1);
}

编辑:经过测试并可在 Firefox、IE 和 Firefox 中使用。 Windows 上的 Chrome。
编辑2:将setTimeout()移动到if块内,道具@vsync。

Does your fix not work? I'm not sure if I understand the question correctly - do you have a demo page? You could try:

if (location.hash) {
  setTimeout(function() {

    window.scrollTo(0, 0);
  }, 1);
}

Edit: tested and works in Firefox, IE & Chrome on Windows.
Edit 2: move setTimeout() inside if block, props @vsync.

醉南桥 2024-09-25 13:26:14

请在此处查看我的答案: Stackoverflow 答案

诀窍是尽快删除主题标签并存储其值供您自己使用

:重要的是,不要将这部分代码放入 $() 或 $(window).load() 函数中,因为为时已晚,并且浏览器已经移至该标记。

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).on('load', function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});

See my answer here: Stackoverflow Answer

The trick is to just remove the hashtag ASAP and store its value for your own use:

It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be too late and the browser already has moved to the tag.

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).on('load', function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});
独自唱情﹋歌 2024-09-25 13:26:14

还有其他方法可以跟踪您所在的选项卡;也许设置一个cookie,或者在隐藏字段中设置一个值,等等。

我想说,如果你不希望页面在加载时跳转,你最好使用这些其他选项之一而不是散列,因为优先使用哈希值的主要原因是为了准确地允许您想要阻止的内容。

另一点 - 如果您的哈希链接与文档中的标签名称不匹配,页面将不会跳转,因此如果您想继续使用哈希,您可以操纵内容,以便标签以不同的方式命名。如果您使用一致的前缀,您仍然可以使用 Javascript 在它们之间跳转。

希望有帮助。

There are other ways of tracking what tab you're on; perhaps setting a cookie, or a value in a hidden field, etc etc.

I would say that if you don't want the page jumping on load, you would be better off using one of these other options rather than the hash, because the main reason for using the hash in preference to them is to allow exactly what you're wanting to block.

Another point - the page won't jump if your hash links don't match the names of the tags in the document, so perhaps if you want to keep using the hash you could manipulate the content so that the tags are named differently. If you use a consistent prefix, you will still be able to use Javascript to jump between then.

Hope that helps.

萌酱 2024-09-25 13:26:14

我使用了 dave1010 的解决方案,但是当我将其放入 $().ready 函数中时,它有点跳动。所以我这样做了:(不在 $().ready 内)

    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);
    }

I used dave1010's solution, but it was a bit jumpy when I put it inside the $().ready function. So I did this: (not inside the $().ready)

    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);
    }
Oo萌小芽oO 2024-09-25 13:26:14
  1. 如果有 http 则浏览器跳转到 地址中的 ://site.com/#abc 哈希值和 id="abc" 的元素可见。因此,您应该默认隐藏该元素:
    如果页面中没有 id=hash 的可见元素,浏览器不会跳转。

  2. 创建一个脚本来检查 url 中的哈希值,然后查找并显示 prrpopriate 元素(默认情况下隐藏)。

  3. 通过将 onclick 事件绑定到链接并指定 return false; 作为 onclick 事件的结果来禁用默认的“类似哈希的链接”行为。

当我实现选项卡时,我写了类似的东西:

    <script>
    $(function () {         
        if (location.hash != "") {
            selectPersonalTab(location.hash);
        }
        else {
            selectPersonalTab("#cards");
        }
    });

    function selectPersonalTab(hash) {
        $("#personal li").removeClass("active");
        $("a[href$=" + hash + "]").closest("li").addClass("active");
        $("#personaldata > div").hide();
        location.hash = hash;
        $(hash).show();
    }

    $("#personal li a").click(function (e) {
        var t = e.target;
        if (t.href.indexOf("#") != -1) {
            var hash = t.href.substr(t.href.indexOf("#"));
            selectPersonalTab(hash);
            return false;
        }
    });
</script>
  1. Browser jumps to <element id="abc" /> if there are http://site.com/#abc hash in the address and the element with id="abc" is visible. So, you just should hide the element by default: <element id="anchor" style="display: none" />.
    If there is no visible element with id=hash at the page, the browser would not jump.

  2. Create a script that checks the hash in url, and then finds and shows the prrpopriate element (that is hidden by default).

  3. Disable default "hash-like link" behaviour by binding an onclick event to a link and specify return false; as a result of onclick event.

When I implemented tabs, I wrote something like that:

    <script>
    $(function () {         
        if (location.hash != "") {
            selectPersonalTab(location.hash);
        }
        else {
            selectPersonalTab("#cards");
        }
    });

    function selectPersonalTab(hash) {
        $("#personal li").removeClass("active");
        $("a[href$=" + hash + "]").closest("li").addClass("active");
        $("#personaldata > div").hide();
        location.hash = hash;
        $(hash).show();
    }

    $("#personal li a").click(function (e) {
        var t = e.target;
        if (t.href.indexOf("#") != -1) {
            var hash = t.href.substr(t.href.indexOf("#"));
            selectPersonalTab(hash);
            return false;
        }
    });
</script>
﹎☆浅夏丿初晴 2024-09-25 13:26:14

没有一个答案对我来说效果不够好,我看到页面跳转到锚点,然后跳到顶部寻找一些解决方案,有些答案根本不起作用,可能事情已经改变了很多年。希望我的功能对某人有所帮助。

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}
木落 2024-09-25 13:26:14

脏CSS仅修复每次使用锚点时保持向上滚动(如果您仍然想使用锚点进行滚动跳转则没有用,对于深度链接非常有用):

.elementsWithAnchorIds::before {
   content: "";
   display: block;
   height: 9999px;
   margin-top: -9999px; //higher thin page height
}

dirty CSS only fix to stay scrolled up every time the anchor is used (not useful if you still want to use anchors for scroll-jumps, very useful for deeplinking):

.elementsWithAnchorIds::before {
   content: "";
   display: block;
   height: 9999px;
   margin-top: -9999px; //higher thin page height
}
感性 2024-09-25 13:26:14

虽然接受的答案确实效果很好,但我确实发现有时,特别是在包含大图像的页面上,滚动条会疯狂地跳跃,

 window.scrollTo(0, 0);

这可能会分散用户的注意力。

我最终确定的解决方案实际上非常简单,那就是在目标上使用与 location.hash 中使用的 ID 不同的 ID

这是其他页面上的链接

<a href="/page/with/tabs#tab2">Some info found in tab2 on tabs page</a>

例如 当然,如果选项卡页面上有 ID 为 tab2 的元素,则窗口将在加载时跳转到该元素。

因此,您可以在 ID 上附加一些内容来阻止它:

<div id="tab2-noScroll">tab2 content</div>

然后您可以在 javascript 中将 "-noScroll" 附加到 location.hash 中:

<script type="text/javascript">
    $(function() {

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;


     tabContent.not(hash + '-noScroll').hide();                           
        if(hash=="") {       //^ here
      $('#tab1-noScroll').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href") + '-noScroll'; 
                                                               //^ and here

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

While the accepted answer does work well, I did find that sometimes, especially on pages containing large images that the scroll bar will jump about wildly using

 window.scrollTo(0, 0);

Which can be quite distracting for the user.

The solution I settled on in the end is actually pretty simple, and that's to use a different ID on the target to the one used in location.hash

Eg:

Here is the link on some other page

<a href="/page/with/tabs#tab2">Some info found in tab2 on tabs page</a>

So of course if there is an element with an ID of tab2 on the tabs page the window will jump to it on load.

So you can append something to the ID to prevent it:

<div id="tab2-noScroll">tab2 content</div>

And then you can append "-noScroll" to location.hash in the javascript:

<script type="text/javascript">
    $(function() {

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;


     tabContent.not(hash + '-noScroll').hide();                           
        if(hash=="") {       //^ here
      $('#tab1-noScroll').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href") + '-noScroll'; 
                                                               //^ and here

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>
请爱~陌生人 2024-09-25 13:26:14

在我的例子中,由于使用 CSS 弹出窗口的锚链接,我使用了这种方式:

只需在单击时首先保存 pageYOffset ,然后将 ScrollTop 设置为:

$(document).on('click','yourtarget',function(){
        var st=window.pageYOffset;
        $('html, body').animate({
                'scrollTop' : st
            });
});

In my case because of using anchor link for CSS popup I've used this way:

Just save the pageYOffset first thing on click and then set the ScrollTop to that:

$(document).on('click','yourtarget',function(){
        var st=window.pageYOffset;
        $('html, body').animate({
                'scrollTop' : st
            });
});
谁对谁错谁最难过 2024-09-25 13:26:14

我想我已经找到了一种无需重做功能即可使用 UI 选项卡的方法。到目前为止我还没有发现任何问题。

    $( ".tabs" ).tabs();
    $( ".tabs" ).not(".noHash").bind("tabsshow", function(event, ui) { 
        window.location.hash = "tab_"+ui.tab.hash.replace(/#/,"");
        return false;
    });

    var selectedTabHash = window.location.hash.replace(/tab_/,"");
    var index = $( ".tabs li a" ).index($(".tabs li a[href='"+selectedTabHash+"']"));
    $( ".tabs" ).not(".noHash").tabs('select', index);

一切都在准备好的事件中。它在哈希值前面加上“tab_”,但在单击和加载哈希值的页面时都可以工作。

I think I've found a way for UI Tabs without redoing the functionality. So far I haven't found any problems.

    $( ".tabs" ).tabs();
    $( ".tabs" ).not(".noHash").bind("tabsshow", function(event, ui) { 
        window.location.hash = "tab_"+ui.tab.hash.replace(/#/,"");
        return false;
    });

    var selectedTabHash = window.location.hash.replace(/tab_/,"");
    var index = $( ".tabs li a" ).index($(".tabs li a[href='"+selectedTabHash+"']"));
    $( ".tabs" ).not(".noHash").tabs('select', index);

All within a ready event. It prepends "tab_" for the hash but work both when clicked and page loaded with hash.

魄砕の薆 2024-09-25 13:26:14

这将与 bootstrap v3 一起使用

$(document).ready(function() {
  if ($('.nav-tabs').length) {
    var hash = window.location.hash;
    var hashEl = $('ul.nav a[href="' + hash + '"]');
    hash && hashEl.tab('show');

    $('.nav-tabs a').click(function(e) {
      e.preventDefault();
      $(this).tab('show');
      window.location.hash = this.hash;
    });

    // Change tab on hashchange
    window.addEventListener('hashchange', function() {
      var changedHash = window.location.hash;
      changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');
    }, false);
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="container">
<ul class="nav nav-tabs">
  <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
  <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade in active">
    <h3>HOME</h3>
    <p>Some content.</p>
  </div>
  <div id="menu1" class="tab-pane fade">
    <h3>Menu 1</h3>
    <p>Some content in menu 1.</p>
  </div>
</div>
</div>

This will work with bootstrap v3

$(document).ready(function() {
  if ($('.nav-tabs').length) {
    var hash = window.location.hash;
    var hashEl = $('ul.nav a[href="' + hash + '"]');
    hash && hashEl.tab('show');

    $('.nav-tabs a').click(function(e) {
      e.preventDefault();
      $(this).tab('show');
      window.location.hash = this.hash;
    });

    // Change tab on hashchange
    window.addEventListener('hashchange', function() {
      var changedHash = window.location.hash;
      changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');
    }, false);
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="container">
<ul class="nav nav-tabs">
  <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
  <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade in active">
    <h3>HOME</h3>
    <p>Some content.</p>
  </div>
  <div id="menu1" class="tab-pane fade">
    <h3>Menu 1</h3>
    <p>Some content in menu 1.</p>
  </div>
</div>
</div>

打小就很酷 2024-09-25 13:26:14

另一种方法

尝试检查页面是否已滚动,然后重置位置:

var scrolled = false;

$(window).scroll(function(){
  scrolled = true;
});

if ( window.location.hash && scrolled ) {
  $(window).scrollTop( 0 );
}

Heres a demo

Another approach

Try checking if the page has been scrolled and only then reset position:

var scrolled = false;

$(window).scroll(function(){
  scrolled = true;
});

if ( window.location.hash && scrolled ) {
  $(window).scrollTop( 0 );
}

Heres a demo

娇俏 2024-09-25 13:26:14

我在 Firefox 中使用上述 setTimeout 方法并没有取得太大成功。

我没有使用 setTimeout,而是使用了 onload 函数:

window.onload = function () {
    if (location.hash) {
        window.scrollTo(0, 0);
    }
};

不幸的是,它仍然存在很多问题。

I did not have much success with the above setTimeout methods in Firefox.

Instead of a setTimeout, I've used an onload function:

window.onload = function () {
    if (location.hash) {
        window.scrollTo(0, 0);
    }
};

It's still very glitchy, unfortunately.

知足的幸福 2024-09-25 13:26:14

我使用这些解决方案并没有取得任何一致的成功。

显然是因为跳转发生在 Javascript => 之前
参考(http://forum.jquery.com/topic/preventing-anchor-jump)

我的解决方案是使用 CSS 默认将所有锚点放置在顶部。

.scroll-target{position:fixed;top:0;left:0;}

然后使用 jquery 滚动到目标锚点的父级,或同级(可能是空 em 标记)

<a class="scroll-target" name="section3"></a><em> </em>

jquery 示例,用于在使用 hash 输入 URL 时滚动
(页面不得已加载到窗口/选项卡中,这涵盖了来自其他/外部来源的链接)

setTimeout(function() {
    if (window.location.hash) {               
        var hash = window.location.hash.substr(1);   
        var scrollPos = $('.scroll-target[name="'+hash+'"]').siblings('em').offset().top; 
        $("html, body").animate({ scrollTop: scrollPos }, 1000);    
    }
}, 1);

此外,您还需要在页面上阻止默认的锚点点击,然后滚动到其目标

<a class="scroll-to" href="#section3">section three</a>

和 jquery

$('a.scroll-to').click(function(){
    var target = $(this).attr('href').substr(1);
    var scrollPos = $('.scroll-target[name="'+target+'"]').siblings('em').offset().top; 
    $("html, body").animate({ scrollTop: scrollPos }, 1000);
    return false;
});

此方法的好处是锚标记目标,在结构上保留在相关内容旁边,尽管它们的 CSS 位置位于顶部。

这应该意味着搜索引擎爬虫不会出现问题。

干杯,我希望这有帮助
格雷

I have not had any consistent success with these solutions.

Apparently due to the fact that the jump happens before Javascript =>
reference(http://forum.jquery.com/topic/preventing-anchor-jump)

My solution is to position all anchors at the top by default with CSS.

.scroll-target{position:fixed;top:0;left:0;}

Then use jquery to scroll to the parent of the target anchor, or a sibling(maybe an empty em tag)

<a class="scroll-target" name="section3"></a><em> </em>

jquery example for scrolling for when URL is entered with hash
(page must not be already loaded in window/tab, this covers links from other/outside sources)

setTimeout(function() {
    if (window.location.hash) {               
        var hash = window.location.hash.substr(1);   
        var scrollPos = $('.scroll-target[name="'+hash+'"]').siblings('em').offset().top; 
        $("html, body").animate({ scrollTop: scrollPos }, 1000);    
    }
}, 1);

Also you'll want to prevent default for anchor clicks while on the page and then scroll to their targets

<a class="scroll-to" href="#section3">section three</a>

and jquery

$('a.scroll-to').click(function(){
    var target = $(this).attr('href').substr(1);
    var scrollPos = $('.scroll-target[name="'+target+'"]').siblings('em').offset().top; 
    $("html, body").animate({ scrollTop: scrollPos }, 1000);
    return false;
});

The good thing about this method is the anchor tag targets, remain structurally beside the relevant content, although their CSS position is at the top.

This should mean that search engine crawlers won't have a problem.

Cheers, I hope this helps
Gray

老旧海报 2024-09-25 13:26:14

尝试这样做以防止客户端在 hashchanged 上进行任何类型的垂直滚动(在事件处理程序内):(

var sct = document.body.scrollTop;
document.location.hash = '#next'; // or other manipulation
document.body.scrollTop = sct;

浏览器重绘)

Try this to prevent client from any kind of vertical scrolling on hashchanged (inside your event handler):

var sct = document.body.scrollTop;
document.location.hash = '#next'; // or other manipulation
document.body.scrollTop = sct;

(browser redraw)

不气馁 2024-09-25 13:26:14

通过这样做解决了我的问题:

// navbar height 
var navHeigth = $('nav.navbar').height();    

// Scroll to anchor function
var scrollToAnchor = function(hash) {
  // If got a hash
  if (hash) {
    // Scroll to the top (prevention for Chrome)
    window.scrollTo(0, 0);
    // Anchor element
    var term = $(hash);

    // If element with hash id is defined
    if (term) {

      // Get top offset, including header height
      var scrollto = term.offset().top - navHeigth;

      // Capture id value
      var id = term.attr('id');
      // Capture name value
      var name = term.attr('name');

      // Remove attributes for FF scroll prevention
      term.removeAttr('id').removeAttr('name');
      // Scroll to element
      $('html, body').animate({scrollTop:scrollto}, 0);

      // Returning id and name after .5sec for the next scroll
      setTimeout(function() {
        term.attr('id', id).attr('name', name);
      }, 500);
    }
  }
};

// if we are opening the page by url
if (location.hash) {
  scrollToAnchor(location.hash);
}

// preventing default click on links with an anchor
$('a[href*="#"]').click(function(e) {
  e.preventDefault();
  // hash value
  var hash = this.href.substr(this.href.indexOf("#"));
  scrollToAnchor(hash);
});`

Solved my promlem by doing this:

// navbar height 
var navHeigth = $('nav.navbar').height();    

// Scroll to anchor function
var scrollToAnchor = function(hash) {
  // If got a hash
  if (hash) {
    // Scroll to the top (prevention for Chrome)
    window.scrollTo(0, 0);
    // Anchor element
    var term = $(hash);

    // If element with hash id is defined
    if (term) {

      // Get top offset, including header height
      var scrollto = term.offset().top - navHeigth;

      // Capture id value
      var id = term.attr('id');
      // Capture name value
      var name = term.attr('name');

      // Remove attributes for FF scroll prevention
      term.removeAttr('id').removeAttr('name');
      // Scroll to element
      $('html, body').animate({scrollTop:scrollto}, 0);

      // Returning id and name after .5sec for the next scroll
      setTimeout(function() {
        term.attr('id', id).attr('name', name);
      }, 500);
    }
  }
};

// if we are opening the page by url
if (location.hash) {
  scrollToAnchor(location.hash);
}

// preventing default click on links with an anchor
$('a[href*="#"]').click(function(e) {
  e.preventDefault();
  // hash value
  var hash = this.href.substr(this.href.indexOf("#"));
  scrollToAnchor(hash);
});`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文