简体   繁体   English

滚动到带有固定标题的锚点位置

[英]Scroll to anchor position with fixed header

I have created a single page vertical scroll.我创建了一个单页垂直滚动。 When the user clicks on an anchor like "about" it will scroll to that position.当用户点击像“about”这样的锚点时,它会滚动到那个位置。 Something to keep in mind is, that I use a fixed header with a height of 80px.需要记住的是,我使用了一个高度为 80px 的固定标题。

Above example works.上面的例子有效。 When I click on "about us" with the anchor "about" it will scroll to the section with the id of "about".当我用锚点“about”点击“about us”时,它会滚动到id为“about”的部分。 Nothing special.没什么特别的。

But the problem is the following.但问题如下。 When I say, I want to navigate visitors to a special place in the one page design.当我说,我想将访问者导航到单页设计中的一个特殊位置。 For example like this: www.mydomain.com/#about - it should scroll directly to that position, when entering above URL.例如像这样:www.mydomain.com/#about - 当输入上面的 URL 时,它应该直接滚动到那个位置。 But this I can't get work.但这我不能得到工作。 I don't know how to explain this because there are a lot of scenarios that happens for me.我不知道如何解释这一点,因为有很多场景发生在我身上。 Like it will scroll directly to the bottom page or it will scroll not specific to that section, it stops to late, or the position is not minus the header that results that the fixed header overlaps the content of that section.就像它会直接滚动到底部页面,或者它不会滚动到特定于该部分,它会停止到很晚,或者位置不减去导致固定标题与该部分内容重叠的标题。 It's important that the target position is minus the fixed header.重要的是target位置减去固定标题。

Beside that I think that I am using unnecessary code for some parts.除此之外,我认为我在某些部分使用了不必要的代码。 Some advice how to improve my code would also be nice.一些关于如何改进我的代码的建议也很好。

A working code you can find here您可以在此处找到工作代码

Code: First part of my code.代码:我的代码的第一部分。 Here I control the click function.这里我控制点击功能。 When the user clicks on a link inside #primary-navwrapper it should do that function.当用户点击#primary-navwrapper内的链接时,它应该执行该功能。 Store the asked hash link inside anchorId and set it to scrollToAnchor function.将询问的哈希链接存储在anchorId并将其设置为 scrollToAnchor 函数。 Then it gets the position of that hash decreased by the fixed header (so the header will not overlap the content).然后它通过固定标头减少该哈希的位置(因此标头不会与内容重叠)。 And update the hash with the current anchorId.并使用当前的 anchorId 更新哈希。

// An offset to push the content down from the top
    var offset = $('#header').outerHeight();


    // Navigation click action
    // Scroll to # HASH ID
    $('#primary-navwrapper li a[href^="#"]').click(function(event) {

        // Prevent from default action to intitiate
        event.preventDefault();

        // The id of the section we want to go to
        var anchorId = $(this).attr('href');

        scrollToAnchor(anchorId);

        return false;
    });


    function scrollToAnchor(anchorId) {

    // Our scroll target : the top position of the section that has the id referenced by our href
    var target = $(anchorId).offset().top - offset;
    //console.log("target" + target);

    // The magic...smooth scrollin' goodness.
    $('html, body').animate({ scrollTop: target }, 500, function () {
        //window.location.hash = '!' + id;
        window.location.hash = anchorId;
    });

}

Does someone has a solution for this or maybe some advice.有人对此有解决方案或一些建议。 Look out to your answer.注意你的答案。

Casper卡斯帕

UPDATED ANSWER更新的答案

This is the working code jsFiddle这是工作代码jsFiddle


PROBLEM SUMMARY问题总结

  1. When a user clicks one of the menus, screen will move to the content section, but it's too close to the header.当用户单击其中一个菜单时,屏幕将移动到内容部分,但它离标题太近了。 There should be spaces between the content area and my header.内容区域和我的标题之间应该有空格。
  2. I need to move screen to the expected content section when a user enters into my homepage with a query string like '#aboutus'当用户使用“#aboutus”等查询字符串进入我的主页时,我需要将屏幕移动到预期的内容部分

This is your core question I could understand so far, and I summarized this for the future helpers for you.这是你目前我能理解的核心问题,我为你未来的帮助者总结了这一点。

I thoroughly checked your codes and found some factors that don't bring you the result you expected.我彻底检查了您的代码,发现了一些无法为您带来预期结果的因素。

First , there was no document.ready() scope.首先,没有document.ready()作用域。 Everything was declared over global scopes.一切都在全局范围内声明。 Well your functions seem to be okay in the global sections, but your click events should be declared in the document.ready() section so that jQuery properly takes them and initilizes them.好吧,您的函数在全局部分似乎没问题,但是您的单击事件应该在document.ready()部分中声明,以便jQuery正确获取它们并初始化它们。

For this reason, your original code doesn't produce the animation when scrolling down to the expected section because it's the browser's default behaviour by href=# , not by your click event.出于这个原因,您的原始代码在向下滚动到预期部分时不会产生动画,因为它是浏览器的默认行为href=# ,而不是您的点击事件。 So I added some of codes to ensure the event call.所以我添加了一些代码来确保事件调用。

And secondly , you didn't have any methods to scroll to the expected content section when your url has a query string like #gallery, #aboutus, and etc .其次,当您的 url 具有查询字符串(如#gallery, #aboutus, and etc时,您没有任何方法可以滚动到预期的内容部分。 So I put some codes for that所以我为此放了一些代码

Please find my ID on the script sheet, then it will locate the exact points where I newly added or editted the existing codes.请在脚本表上找到我的 ID,然后它会找到我新添加或编辑现有代码的确切点。 I commented a lot我评论了很多


FYI供参考

There's a thing that I couldn't figure out.有一件事我想不通。 Your code is supposed to work nicely, but IE scrolls differently.您的代码应该可以很好地工作,但 IE 的滚动方式不同。 Since you use event.preventDefault() on your click event, the default scrolling action by href=#something shouldn't work.由于您在单击事件上使用event.preventDefault() ,因此href=#something的默认滚动操作href=#something应该起作用。 But it does the behaviour in IE whereas chrome shows the expected result.但它在 IE 中执行行为,而 chrome 显示预期结果。 ( what I'm telling you here is that the task to leave spaces for your sticky header ) (我在这里告诉您的是为粘性标题留出空间的任务)

I thought at first that this is the IE bug, but it wasn't.起初我以为这是 IE 的错误,但事实并非如此。 It should work like this example I made.它应该像我制作的这个例子一样工作 well, I can't dig into this problem any further.好吧,我不能再深入研究这个问题了。 It's your time.是你的时候了。


OLD ANSWER旧答案

In this case, you need to get the query string and let your scrollToAnchor takes it at the $(document).ready() point.在这种情况下,您需要获取查询字符串并让您的scrollToAnchor$(document).ready()点获取它。

var queryString = window.location.hash;    
scrollToAnchor(queryString);

I tested on your fiddle and it works.我在你的小提琴上测试过,它有效。

And please make sure your scrollToAnchor doesn't throw an error because of an empty parameter.并且请确保您的scrollToAnchor不会因为参数为空而引发错误。 The emptry string "" and null object causes an error in your scrollToAnchor空字符串""null对象会导致scrollToAnchor出现错误

Put a safeguard like this.放置这样的保护措施。

function scrollToAnchor(anchorId) {
    if ( anchorId == null || anchorId == "" ) {
        return false;
    }
    .
    .

But this safeguard also cannot prevent the error when a user mistyped querystring, like #avoutus which doesn't exist on your document.但是,当用户输入错误的查询字符串(如#avoutus中不存在的#avoutus ,此保护措施也无法防止错误。 So I recommend you avoid $(anchorId).offset().top - offset;所以我建议你避免$(anchorId).offset().top - offset; this kind of code.这种代码。

Selecting an element directly via such dynamic variables can't gurantee a safe object unless they are totally under your control.直接通过这样的动态变量选择一个元素不能保证一个安全的对象,除非它们完全在你的控制之下。

This worked for me.这对我有用。

html {
  scroll-padding-top: 70px; /* height of sticky header */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM