这是我的HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
<title>A+Tec</title>
<style type="text/css" >
* {
  margin: 0px;
  padding: 0px;
}
#wrapper {
  width: 100%;
  height: auto;
  background-color: #ABEBC1;
  position: fixed;
}

#nav {
  width: 1400px;
  height: auto;
  margin: auto;
}

.buttons {
  height: 25x;
  width: 200px;
  background-color: #ABEBC1;
  background-repeat: repeat-x;
  float: left;
  margin: 0px 10px;
  text-align: center;
  font-family:"Arial Rounded MT Bold", Arial, Helvetica, sans-serif;
}
</style>
</head>

<body>

<div id="wrapper">
  <div id="nav">
  <div class="buttons">
  </div>
  <div class="buttons"><a href="#C4">About Us</a></div>
  <div class="buttons">Our Staff</div>
  <div class="buttons">New Admissions</div>
  <div class="buttons">A-Level</div>
  <div class="buttons">GCSE</div>
  <div class="buttons">Contact Us</div>
  </div>
</div>
<br/>
<p>
<a href="#C4">See also Chapter 4.</a>
</p>
<h2>Chapter 1</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 3</h2>
<p>This chapter explains ba bla bla</p>

<h2><a id="C4">Chapter 4</a></h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 5</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 6</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 7</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 8</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 9</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 10</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 11</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 12</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 13</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 14</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 15</a></h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 16</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 17</h2>
<p>This chapter explains ba bla bla</p>
</body>
</html>


我已经从w3schools的tryit中复制并粘贴了代码,该代码使您可以使用超链接跳转到网站的任何部分,网址为:http://www.w3schools.com/html/tryit.asp?filename=tryhtml_link_locations。当我单击链接“第4章”时,它跳到了第2章,当我单击顶部div中的“关于我们”时,它转到了同一位置。即使我尝试跳至文档的不同部分,它仍会跳至同一部分。为什么是这样?

编辑:上面似乎工作正常,当我跳到一个标题时,它隐藏在顶部的栏后面。有什么方法可以使其跳到顶部栏下方的位置吗?

谢谢

最佳答案

关于ID,您无需将其放在标题内的<a>上。只需使用此:

<h2 id="C4">Chapter 4</h2>


关于清除固定标头,以下是有关此问题的一些方便文章:


http://css-tricks.com/hash-tag-links-padding/
http://nicolasgallagher.com/jump-links-and-viewport-positioning/demo/


关于跳到第二章的链接,可能取决于浏览器窗口的高度。它只能在内容允许的范围内下降。如果使用:target,您仍然会看到第4章标题为目标。例如

#C4:target {background: red;}

09-07 19:04