代码之家  ›  专栏  ›  技术社区  ›  DuchSuvaa

如何对另一页上的链接应用偏移量

  •  1
  • DuchSuvaa  · 技术社区  · 6 年前

    我有一个网站,基本上是80%索引.html再加上一些小的子页面。 但是,导航已经位置:固定和比如说100px的高度

    <a href="#section">
    

    需要100像素的偏移量。 我是通过jQuery实现的(我将不考虑特定部分的所有if):

    $("#navigation a").click(function() {
        event.preventDefault();
        var offset = $("#section1").offset().top - 100;
        $(window).scrollTop(offset);
    }
    

    问题是当我导航到索引.html从子页面来看,这个技巧不起作用,所以我不能在子页面上使用这个函数,而只是“允许默认值”。

    有没有一种方法可以导航到其他html文档的#部分并具有适当的偏移量(不能硬编码)?

    1 回复  |  直到 6 年前
        1
  •  1
  •   frontend-trends    6 年前

    假定在索引.html所有具有类部分的目标。使用这个CSS片段,固定导航不会隐藏任何目标。

    body {
       padding-top: 60px;
       margin-top: 0px;
    }
    
     #fixed-nav { 
       position:fixed;
       height:50px;
       line-height:50px;
       vertical-align:middle;    
       background:#000;
       top:0;
       left:0;
       right:0;
       color:#FFF;
       padding-left:5px;
    }
    
    #fixed-nav a {
      color: white;
      margin-right: 10px;
      text-decoration: none;
    }
    
    #sections .section {
      height:400px;
      padding-left:5px;
    }
    
    #sections .section:before { 
      display: block; 
      content: " "; 
      margin-top: -60px; 
      height: 60px; 
      visibility: hidden; 
    <div id="fixed-nav">
       <a href="#target-1">To target 1</a>
       <a href="#target-2">To target 2</a>
       <a href="#target-3">To target 3</a>
       <a href="#target-4">To target 4</a>
       <a href="#target-5">To target 5</a>
    </div>
    
    <div id="sections">
      <div class="section" id="target-1">
        Target 1
      </div>
      <div class="section" id="target-2">
        Target 2
      </div>
      <div class="section" id="target-3">
        Target 3
      </div>
      <div class="section" id="target-4">
        Target 4
      </div>
      <div class="section" id="target-5">
        Target 5
      </div>
    </div>