创建超链接

超链接确实很重要 - 它们使网络成为网络。本文展示了创建链接所需的语法,并讨论了链接最佳实践。

¥Hyperlinks are really important — they are what makes the Web a web. This article shows the syntax required to make a link, and discusses link best practices.

先决条件: 熟悉基本的 HTML,如 HTML 入门 中所述。HTML 文本格式,如 HTML 文本基础知识 中所述。
目标: 了解如何有效地实现超链接,并将多个文件链接在一起。

什么是超链接?

¥What is a hyperlink?

超链接是网络提供的最令人兴奋的创新之一。它们从一开始就是 Web 的一个功能,也是 Web 之所以成为 Web 的原因。超链接使我们能够将文档链接到其他文档或资源、链接到文档的特定部分或使应用可在网址上使用。几乎所有网页内容都可以转换为链接,以便在单击或以其他方式激活时,网页浏览器会转到另一个网址 (URL)。

¥Hyperlinks are one of the most exciting innovations the Web has to offer. They've been a feature of the Web since the beginning, and are what makes the Web a web. Hyperlinks allow us to link documents to other documents or resources, link to specific parts of documents, or make apps available at a web address. Almost any web content can be converted to a link so that when clicked or otherwise activated the web browser goes to another web address (URL).

注意:URL 可以指向 HTML 文件、文本文件、图片、文本文档、视频和音频文件或 Web 上的任何其他内容。如果网络浏览器不知道如何显示或处理文件,它会询问你是否要打开该文件(在这种情况下,打开或处理文件的职责将传递给设备上合适的原生应用) 或下载该文件(在这种情况下你可以稍后尝试处理它)。

¥Note: A URL can point to HTML files, text files, images, text documents, video and audio files, or anything else that lives on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on).

例如,BBC 主页包含许多链接,这些链接不仅指向多个新闻报道,还指向网站的不同区域(导航功能)、登录/注册页面(用户工具)等。

¥For example, the BBC homepage contains many links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools), and more.

front page of bbc.co.uk, showing many news items, and navigation menu functionality

链接剖析

¥Anatomy of a link

基本链接是通过将文本或其他内容封装在 <a> 元素内并使用包含 Web 地址的 href 属性(也称为超文本引用或目标)来创建的。

¥A basic link is created by wrapping the text or other content inside an <a> element and using the href attribute, also known as a Hypertext Reference, or target, that contains the web address.

html
<p>
  I'm creating a link to
  <a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
</p>

这给了我们以下结果:我正在创建一个指向 Mozilla 主页 的链接。

¥This gives us the following result:\ I'm creating a link to the Mozilla homepage.

块级链接

¥Block level links

前面说过,几乎任何内容都可以做成链接,甚至是 block-level elements。如果要将标题元素设为链接,请将其封装在锚点 (<a>) 元素中,如以下代码片段所示:

¥As mentioned before, almost any content can be made into a link, even block-level elements. If you want to make a heading element a link then wrap it in an anchor (<a>) element as shown in the following code snippet:

html
<a href="https://web.nodejs.cn/en-US/">
  <h1>MDN Web Docs</h1>
</a>
<p>
  Documenting web technologies, including CSS, HTML, and JavaScript, since 2005.
</p>

这会将标题变成链接:

¥This turns the heading into a link:

图片链接

¥Image links

如果你想要将图片制作为链接,请使用 <a> 元素来封装由 <img> 元素引用的图片文件。下面的示例使用相对路径来引用本地存储的 SVG 图片文件。

¥If you have an image you want to make into a link, use the <a> element to wrap the image file referenced with the <img> element. The example below uses a relative path to reference a locally stored SVG image file.

css
img {
  height: 100px;
  width: 150px;
  border: 1px solid gray;
}
html
<a href="https://web.nodejs.cn/en-US/">
  <img src="mdn_logo.svg" alt="MDN Web Docs" />
</a>

这使得 MDN 徽标成为一个链接:

¥This makes the MDN logo a link:

注意:你将在以后的文章中了解有关在 Web 上使用图片的更多信息。

¥Note: You'll find out more about using images on the Web in a future article.

使用标题属性添加支持信息

¥Adding supporting information with the title attribute

你可能想要添加到链接的另一个属性是 title。标题包含有关链接的附加信息,例如页面包含哪种信息,或者网站上需要注意的事项。

¥Another attribute you may want to add to your links is title. The title contains additional information about the link, such as which kind of information the page contains, or things to be aware of on the website.

html
<p>
  I'm creating a link to
  <a
    href="https://www.mozilla.org/en-US/"
    title="The best place to find more information about Mozilla's
          mission and how to contribute">
    the Mozilla homepage</a>.
</p>

这给我们提供了以下结果,并将鼠标悬停在链接上将标题显示为工具提示:

¥This gives us the following result and hovering over the link displays the title as a tooltip:

注意:链接标题仅在鼠标悬停时显示,这意味着依靠键盘控制或触摸屏导航网页的人们将难以访问标题信息。如果标题的信息对于页面的可用性确实很重要,那么你应该以所有用户都可以访问的方式呈现它,例如将其放在常规文本中。

¥Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls or touchscreens to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of the page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

主动学习:创建你自己的示例链接

¥Active learning: creating your own example link

使用本地代码编辑器和我们的 入门模板.html 创建 HTML 文档。

¥Create an HTML document using your local code editor and our getting started template.

  • 在 HTML 正文中,添加一个或多个段落或你已知的其他类型的内容。
  • 将部分内容改为链接。
  • 包括标题属性。

URL 和路径快速入门

¥A quick primer on URLs and paths

要完全理解链接目标,你需要了解 URL 和文件路径。本节为你提供实现此目标所需的信息。

¥To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.

URL(即统一资源定位符)是定义某些内容在 Web 上的位置的文本字符串。例如,Mozilla 的英文主页位于 https://www.mozilla.org/en-US/

¥A URL, or Uniform Resource Locator is a string of text that defines where something is located on the Web. For example, Mozilla's English homepage is located at https://www.mozilla.org/en-US/.

URL 使用路径来查找文件。路径指定你感兴趣的文件在文件系统中的位置。让我们看一个目录结构的示例,请参阅 creating-hyperlinks 目录。

¥URLs use paths to find files. Paths specify where the file you're interested in is located in the filesystem. Let's look at an example of a directory structure, see the creating-hyperlinks directory.

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

该目录结构的根称为 creating-hyperlinks。在本地使用网站时,你将拥有一个包含整个网站的目录。在根目录中,我们有一个 index.html 文件和一个 contacts.html.txt 文件。在真实的网站中,index.html 将是我们的主页或登陆页面(充当网站或网站特定部分的入口点的网页)。

¥The root of this directory structure is called creating-hyperlinks. When working locally with a website, you'll have one directory that contains the entire site. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).

我们的根目录中还有两个目录 - pdfsprojects。它们各自都有一个文件 - 分别是 PDF (project-brief.pdf) 和 index.html 文件。请注意,一个项目中可以有两个 index.html 文件,只要它们位于不同的文件系统位置即可。第二个 index.html 可能是项目相关信息的主要登陆页面。

¥There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note that you can have two index.html files in one project, as long as they're in different filesystem locations. The second index.html would perhaps be the main landing page for project-related information.

  • 同一目录:如果你想在 index.html(顶层 index.html)内包含指向 contacts.html 的超链接,你可以指定要链接到的文件名,因为它与当前文件位于同一目录中。你将使用的 URL 是 contacts.html
    html
    <p>
      Want to contact a specific staff member? Find details on our
      <a href="contacts.html">contacts page</a>.
    </p>
    
  • 向下移动到子目录:如果你想在 index.html(顶层 index.html)内包含指向 projects/index.html 的超链接,则需要先进入 projects 目录,然后再指示要链接到的文件。这是通过指定目录名称,然后是正斜杠,然后是文件名来完成的。你将使用的 URL 是 projects/index.html
    html
    <p>Visit my <a href="projects/index.html">project homepage</a>.</p>
    
  • 返回到父目录:如果你想在 projects/index.html 内包含指向 pdfs/project-brief.pdf 的超链接,则必须向上移动一个目录级别,然后返回到 pdfs 目录。要进入目录,请使用两个点 - .. - 因此你将使用的 URL 是 ../pdfs/project-brief.pdf
    html
    <p>A link to my <a href="../pdfs/project-brief.pdf">project brief</a>.</p>
    

注意:如果需要,你可以将这些功能的多个实例组合成复杂的 URL,例如:../../../complex/path/to/my/file.html

¥Note: You can combine multiple instances of these features into complex URLs, if needed, for example: ../../../complex/path/to/my/file.html.

文档片段

¥Document fragments

可以链接到 HTML 文档的特定部分(称为文档片段),而不仅仅是文档的顶部。为此,你首先必须为要链接的元素分配 id 属性。通常链接到特定标题是有意义的,因此看起来如下所示:

¥It's possible to link to a specific part of an HTML document, known as a document fragment, rather than just to the top of the document. To do this you first have to assign an id attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

html
<h2 id="Mailing_address">Mailing address</h2>

然后,要链接到该特定 id,你可以将其包含在 URL 末尾,前面加上井号/井号符号 (#),例如:

¥Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol (#), for example:

html
<p>
  Want to write us a letter? Use our
  <a href="contacts.html#Mailing_address">mailing address</a>.
</p>

你甚至可以单独使用文档片段引用来链接到当前文档的另一部分:

¥You can even use the document fragment reference on its own to link to another part of the current document:

html
<p>
  The <a href="#Mailing_address">company mailing address</a> can be found at the
  bottom of this page.
</p>

绝对 URL 与相对 URL

¥Absolute versus relative URLs

你在网络上会遇到的两个术语是绝对 URL 和相对 URL:

¥Two terms you'll come across on the Web are absolute URL and relative URL:

绝对网址:指向由其在网络上的绝对位置定义的位置,包括 protocoldomain name。例如,如果将 index.html 页面上传到位于 Web 服务器根目录内名为 projects 的目录,并且该网站的域是 https://www.example.com,则该页面将在 https://www.example.com/projects/index.html 处可用(甚至只是 https://www.example.com/projects/,因为大多数 Web 服务器只是看起来) 如果 URL 中未指定,则加载诸如 index.html 之类的登陆页面。)

¥absolute URL: Points to a location defined by its absolute location on the web, including protocol and domain name. For example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the website's domain is https://www.example.com, the page would be available at https://www.example.com/projects/index.html (or even just https://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it isn't specified in the URL.)

绝对 URL 将始终指向同一位置,无论在何处使用。

¥An absolute URL will always point to the same location, no matter where it's used.

相对网址:指向与你链接的文件相关的位置,更像我们在上一节中看到的那样。例如,如果我们想从 https://www.example.com/projects/index.html 的示例文件链接到同一目录中的 PDF 文件,则 URL 就是文件名 - project-brief.pdf - 不需要额外的信息。如果 PDF 在 projects 内名为 pdfs 的子目录中可用,则相对链接将为 pdfs/project-brief.pdf(等效的绝对 URL 将为 https://www.example.com/projects/pdfs/project-brief.pdf。)

¥relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at https://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be https://www.example.com/projects/pdfs/project-brief.pdf.)

相对 URL 将指向不同的位置,具体取决于你引用的文件的实际位置 - 例如,如果我们将 index.html 文件从 projects 目录移出并移至网站的根目录(顶层,不在任何目录中) ,其中的 pdfs/project-brief.pdf 相对 URL 链接现在将指向位于 https://www.example.com/pdfs/project-brief.pdf 的文件,而不是位于 https://www.example.com/projects/pdfs/project-brief.pdf 的文件。

¥A relative URL will point to different places depending on the actual location of the file you refer from — for example if we moved our index.html file out of the projects directory and into the root of the website (the top level, not in any directories), the pdfs/project-brief.pdf relative URL link inside it would now point to a file located at https://www.example.com/pdfs/project-brief.pdf, not a file located at https://www.example.com/projects/pdfs/project-brief.pdf.

当然,project-brief.pdf 文件和 pdfs 文件夹的位置不会因为你移动了 index.html 文件而突然改变 - 这会让你的链接指向错误的地方,所以如果点击它就不起作用。你需要小心!

¥Of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!

链接最佳实践

¥Link best practices

编写链接时需要遵循一些最佳实践。现在让我们看看这些。

¥There are some best practices to follow when writing links. Let's look at these now.

使用清晰的链接措辞

¥Use clear link wording

在你的页面上添加链接很容易。这还不够。我们需要让所有读者都可以访问我们的链接,无论他们当前的背景如何以及他们喜欢哪种工具。例如:

¥It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

  • 屏幕阅读器用户喜欢在页面上的链接之间跳来跳去,以及脱离上下文阅读链接。
  • 搜索引擎使用链接文本来索引目标文件,因此最好在链接文本中包含关键字以有效描述链接的内容。
  • 视觉读者浏览页面而不是阅读每个单词,他们的眼睛会被突出的页面功能所吸引,例如链接。他们会发现描述性链接文本很有用。

我们来看一个具体的例子:

¥Let's look at a specific example:

好的链接文本:下载火狐浏览器

¥Good link text: Download Firefox

html
<p><a href="https://www.mozilla.org/firefox/">Download Firefox</a></p>

错误的链接文本:点击这里 下载火狐浏览器

¥Bad link text: Click here to download Firefox

html
<p>
  <a href="https://www.mozilla.org/firefox/">Click here</a> to download Firefox
</p>

其他提示:

¥Other tips:

  • 不要在链接文本中重复 URL — URL 看起来很难看,当屏幕阅读器逐个字母地读出它们时,听起来更难看。
  • 不要在链接文本中说 "link" 或 "链接到" — 这只是噪音。屏幕阅读器告诉人们有一个链接。视觉用户也会知道有一个链接,因为链接通常采用不同的颜色和下划线样式(此约定通常不应该被打破,因为用户已经习惯了)。
  • 保持链接文本尽可能短 - 这很有帮助,因为屏幕阅读器需要解释整个链接文本。
  • 最大限度地减少同一文本的多个副本链接到不同位置的情况。如果存在脱离上下文且标记为 "点击这里"、"点击这里"、"点击这里" 的链接列表,这可能会给屏幕阅读器用户带来问题。

链接到非 HTML 资源 — 留下清晰的路标

¥Linking to non-HTML resources — leave clear signposts

当链接到要下载(如 PDF 或 Word 文档)、流式传输(如视频或音频)或具有其他潜在意外效果(打开弹出窗口)的资源时,你应该添加清晰的措辞以减少任何混乱。

¥When linking to a resource that will be downloaded (like a PDF or Word document), streamed (like video or audio), or has another potentially unexpected effect (opens a popup window), you should add clear wording to reduce any confusion.

例如:

¥For example:

  • 如果你使用的是低带宽连接,请单击链接,然后会意外开始数兆字节的下载。

让我们看一些例子,看看这里可以使用什么样的文本:

¥Let's look at some examples, to see what kind of text can be used here:

html
<p>
  <a href="https://www.example.com/large-report.pdf">
    Download the sales report (PDF, 10MB)
  </a>
</p>

<p>
  <a href="https://www.example.com/video-stream/" target="_blank">
    Watch the video (stream opens in separate tab, HD quality)
  </a>
</p>

链接到下载时使用下载属性

¥Use the download attribute when linking to a download

当你链接到要下载而不是在浏览器中打开的资源时,可以使用 download 属性提供默认保存文件名。以下示例包含最新 Windows 版本 Firefox 的下载链接:

¥When you are linking to a resource that's to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:

html
<a
  href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
  download="firefox-latest-64bit-installer.exe">
  Download Latest Firefox for Windows (64-bit) (English, US)
</a>

主动学习:创建导航菜单

¥Active learning: creating a navigation menu

对于本练习,我们希望你将一些页面与导航菜单链接在一起以创建一个多页面网站。这是创建网站的一种常见方式 - 每个页面都使用相同的页面结构,包括相同的导航菜单,因此当单击链接时,给人的印象是你停留在同一个地方,并且显示不同的内容 被抚养长大。

¥For this exercise, we'd like you to link some pages together with a navigation menu to create a multipage website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

你需要制作以下四个页面的本地副本,全部位于同一目录中。有关完整的文件列表,请参阅 navigation-menu-start 目录:

¥You'll need to make local copies of the following four pages, all in the same directory. For a complete file list, see the navigation-menu-start directory:

你应该:

¥You should:

  1. 在一页上的指定位置添加无序列表,其中包括要链接到的页面的名称。导航菜单通常只是链接列表,因此这在语义上是可以的。
  2. 将每个页面名称更改为该页面的链接。
  3. 将导航菜单复制到每个页面。
  4. 在每个页面上,仅删除指向同一页面的链接 - 页面包含指向其自身的链接会令人困惑且不必要。而且,缺少链接可以很好地视觉提醒你当前所在的页面。

完成的示例应类似于以下页面:

¥The finished example should look similar to the following page:

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

注意:如果你遇到困难,或者不确定自己是否正确,可以检查 navigation-menu-marked-up 目录以查看正确答案。

¥Note: If you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

电子邮件链接

¥Email links

可以创建链接或按钮,单击这些链接或按钮会打开新的外发电子邮件,而不是链接到资源或页面。这是使用 <a> 元素和 mailto: URL 方案完成的。

¥It's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the <a> element and the mailto: URL scheme.

在最基本和最常用的形式中,mailto: 链接表示目标收件人的电子邮件地址。例如:

¥In its most basic and commonly used form, a mailto: link indicates the email address of the intended recipient. For example:

html
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>

这会产生一个如下所示的链接:发送电子邮件至无处

¥This results in a link that looks like this: Send email to nowhere.

事实上,电子邮件地址是可选的。如果你省略它并且你的 href 是 "邮寄地址:",则用户的电子邮件客户端将打开一个新的外发电子邮件窗口,但没有目标地址。这通常很有用,因为用户可以单击 "分享" 链接将电子邮件发送到他们选择的地址。

¥In fact, the email address is optional. If you omit it and your href is "mailto:", a new outgoing email window will be opened by the user's email client with no destination address. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

指定细节

¥Specifying details

除了电子邮件地址之外,你还可以提供其他信息。事实上,任何标准邮件标头字段都可以添加到你提供的 mailto URL 中。其中最常用的是 "subject"、"cc" 和 "body"(这不是真正的标头字段,但允许你为新电子邮件指定简短的内容消息)。每个字段及其值都被指定为查询项。

¥In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

下面是一个包含抄送、密件抄送、主题和正文的示例:

¥Here's an example that includes a cc, bcc, subject and body:

html
<a
  href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
  Send mail with cc, bcc, subject and body
</a>

注意:每个字段的值必须使用非打印字符(制表符、回车符和分页符等不可见字符)和空格 percent-escaped 进行 URL 编码。另请注意,使用问号 (?) 将主 URL 与字段值分隔开,并使用与号 (&) 分隔 mailto: URL 中的每个字段。这是标准的 URL 查询表示法。阅读 获取方法 了解 URL 查询表示法更常用的用途。

¥Note: The values of each field must be URL-encoded with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also, note the use of the question mark (?) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto: URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more commonly used for.

以下是其他一些 mailto URL 示例:

¥Here are a few other sample mailto URLs:

测试你的技能!

¥Test your skills!

你已读完本文,但你还记得最重要的信息吗?在继续之前,你可以找到一些进一步的测试来验证你是否已保留此信息 - 请参阅 测试你的技能:链接

¥You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Links.

概括

¥Summary

无论如何,现在链接就这样了!当你开始研究链接的样式时,你将在课程稍后返回链接。接下来的 HTML,我们将返回文本语义并查看一些你会发现有用的更高级/不寻常的功能 - 高级文本格式设置 是你的下一站。

¥That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.