6.3 创建锚

通常,激活一个链接会将用户带到对应网页的顶端。如果要想用户跳至网页的特定区域,可以创建一个,并在链接中引用该锚,参见图6.3.1和图6.3.2。

  1. ...
  2. <body>
  3.  
  4. <h1>Frankie and Johnny</h1>
  5.  
  6. <header>
  7. <h2>Table of Contents</h2>
  8. <nav>
  9. <ul>
  10. <li><a href="#intro">Introduction</a></li>
  11. <li><a href="#main-characters">Description of the Main Characters</a></li>
  12. <li><a href="#rising-action">Rising Action</a></li>
  13. </ul>
  14. </nav>
  15. </header>
  16.  
  17. <article>
  18. <h2 id="intro">Introduction</h2>
  19. <p>This is the intro. If I could think of enough things to write about, it could span a few pages, giving all the introductory information that an introduction should introduce.</p>
  20.  
  21. <h2 id="main-characters">Description of the Main Characters</h2>
  22. <p>Frankie and Johnny are the main characters. She's jealous, and seems to have a reason to be. He's a sleaze, and will pay the price.</p>
  23.  
  24. <h2 id="rising-action">Rising Action</h2>
  25. <p>This is where everything starts happening. Johnny goes out, without Frankie, without even tellin' her where he's going. She's not crazy about it, but she lets him go. A while later, she gets thirsty and decides to go down to the corner bar for some beer. Chatting with the bartender, she learns that Johnny has been there with no other than Nellie Bly. Furious, she catches the crosstown bus to find him.</p>
  26. </article>
  27.  
  28. </body>
  29. </html>

图6.3.1 每个以#开头的链接href值都指向拥有相应id(不含#)的元素。例如,Rising Action指向

Rising Action

。可以为任何元素指定id,只要任何给定的id在一个页面中只存在一次(参见3.15节)。这个例子还让你提前看到了无序列表(ul)的应用。无序列表是目前万维网上使用频率最高的列表类型(第15章将深入讨论列表)

  1. ...
  2. <header>
  3. <h2>Table of Contents</h2>
  4. <nav>
  5. <ul>
  6. <li><a href="#intro"> Introduction</a></li>
  7. ...
  8. </ul>
  9. </nav>
  10. </header>
  11.  
  12. <article>
  13. <section id="intro">
  14. <h2>Introduction</h2>
  15. <p>This is the intro...</p>
  16. </section>
  17.  
  18. <section id="main-characters">
  19. <h2>Description of the Main Characters</h2>
  20. ...
  21. </section>
  22.  
  23. <section id="rising-action">
  24. <h2>Rising Action</h2>
  25. ...
  26. </section>
  27. </article>
  28.  
  29. </body>
  30. </html>

图6.3.2 第一个例子(图6.3.1)设计得很简单,只是为了演示锚的基本用法。不过,可以将每个答案放入一个section元素以进一步增强语义,同时将id放在这些元素内,而不是放在标题里。这这些内容的方法(未在让它们成为article父元素的区块。另一种标记这里演示)是将每个答案视为单独的article,这可以通过移除article父元素,并将每个section改为article实现。这取决于你希望以哪种方式描述你的内容含义(你认为这些答案是一篇文章还是各自独立的文章)

创建锚的步骤

  • 将光标放在希望用户跳转至的元素的开始标记里。

  • 输入id="anchor-name",其中anchor-name是在内部用来标识网页中这部分内容的文字。一定要在元素名称和id之间保留一个空格,例如

提示 为锚id赋予有意义的名称,增强HTML文档的语义丰富度。换句话说,避免使用anchor1item5这样的id

 

提示 id中不能使用空格,应该用短横线分隔不同的单词。

 

提示 在某些情况下,可能需要在每个内容区块的下方包含一个指回目录的链接(你可能已经习惯于看到它们了,它们通常显示为“返回顶部”)。不过,如果你的页面有好几个长的区块,可以考虑将它分成多个页面。