JavaScript issue with scrollTo() in Chrome

前端 未结 2 665
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 05:31

I try to create a web page with a fixed navigation bar at the top that covers the content underneath. When loading the page with an anchor in the url the normal behaviour is

相关标签:
2条回答
  • 2020-12-10 06:14

    I would suggest avoiding the use of JavaScript in favor of creating a dedicated anchor element and then offsetting it above the heading by at least your header height.

    This has already been well described in https://stackoverflow.com/a/13184714/5951116.

    Your code would then look something like this:

    <div id='navi'>
      <a href='./test2.htm'>Menu</a>
    </div>
    <div id='main'>
      <div id='spacer'></div>
      <div class='article-wrapper'>
        <a class='anchor' id='1'></a>
        <h3 id='1'>Heading 1</h3><p class='style1'></p>
      </div>
      <div class='article-wrapper'>
        <a class='anchor' id='2'></a>
        <h3 id='2'>Heading 2</h3><p class='style1'></p>
      </div>
      ...
    </div>
    
    #navi {
      height: 50px;
    }
    
    #main a.anchor {
        display: block;
        position: relative;
        top: -50px;
        visibility: hidden;
    }
    

    Or use CSS variables to remove as much tight coupling as possible:

    :root {
      --header-height: 50px;
    }
    
    #navi {
      height: var(--header-height);
    }
    
    #main a.anchor {
        display: block;
        position: relative;
        top: -var(--header-height);
        visibility: hidden;
    }
    
    0 讨论(0)
  • 2020-12-10 06:29

    Chrome is so fast that your scrollTo() action fires before Chrome's default scroll to html anchor event.

    Give it a tiny delay by using

    setTimeout(function() {window.scrollTo(0, y);},1)
    

    Or simply avoid using the actual element id as hash name

    instead of using

    test.htm#6

    use

    test.htm#link_6

    then you can get the real id by doing something like

    window.location.hash.split('_')[1]
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题