如何对另一页上的 #link 应用偏移量
How to apply an offset to a #link on another page
我得到的网站基本上是 80% index.html 加上一些小的子页面。
Index.html 分为几个部分。
然而,导航有 position:fixed 和高度 - 比如说 - 100px,所以链接像
<a href="#section">
需要 100 像素的偏移量。
我通过 jQuery 实现它(我将保留特定部分的所有 ifs):
$("#navigation a").click(function() {
event.preventDefault();
var offset = $("#section1").offset().top - 100;
$(window).scrollTop(offset);
}
问题是当我从子页面导航到 index.html 时,这个技巧不起作用,所以我不能在子页面上使用这个功能,而只是 "allow default".
有没有一种方法可以导航到另一个 html 文档的 #section 并具有适当的偏移量(不能硬编码)?
您可以在没有 Javascript 的情况下实现此目的。
假定 index.html 所有目标都具有 class 部分。使用此 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>
我得到的网站基本上是 80% index.html 加上一些小的子页面。 Index.html 分为几个部分。 然而,导航有 position:fixed 和高度 - 比如说 - 100px,所以链接像
<a href="#section">
需要 100 像素的偏移量。 我通过 jQuery 实现它(我将保留特定部分的所有 ifs):
$("#navigation a").click(function() {
event.preventDefault();
var offset = $("#section1").offset().top - 100;
$(window).scrollTop(offset);
}
问题是当我从子页面导航到 index.html 时,这个技巧不起作用,所以我不能在子页面上使用这个功能,而只是 "allow default".
有没有一种方法可以导航到另一个 html 文档的 #section 并具有适当的偏移量(不能硬编码)?
您可以在没有 Javascript 的情况下实现此目的。
假定 index.html 所有目标都具有 class 部分。使用此 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>