html - 有相对于​​ root 的链接?

标签 html location-href

有没有办法让页面上的所有链接都相对于根目录?

例如,在 www.example.com/fruits/apples/apple.html 上,我可以有一个链接说:

<a href="fruits/index.html">Back to Fruits List</a>

此链接会指向 www.example.com/fruits/apples/fruits/index.html 还是 www.example.com/fruits/index.html ?如果是第一个,有没有办法让它指向第二个?

最佳答案

根目录相关 URL 以 / 开头字符,看起来像 <a href="/directoryInRoot/fileName.html">link text</a> .

您发布的链接:<a href="fruits/index.html">Back to Fruits List</a>正在链接到位于名为 fruits 的目录中的 html 文件, 该目录与出现此链接的 html 页面位于同一目录中。

要使其成为相对于根目录的 URL,请将其更改为:

<a href="/fruits/index.html">Back to Fruits List</a>

编辑以回应问题,在评论中,来自 OP:

So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?

是的,在 URL 前,在 href 中或 src属性,带有 /将使路径相对于根目录。例如,给定位于 www.example.com/fruits/apples.html 的 html 页面, ahref="/vegetables/carrots.html"将链接到页面 www.example.com/vegetables/carrots.html .

base tag元素允许您指定该页面的 base-uri(尽管必须将 base 标记添加到需要使用特定基的每个页面,为此我我们将简单地引用 W3 的例子:

For example, given the following BASE declaration and A declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
   <TITLE>Our Products</TITLE>
   <BASE href="http://www.aviary.com/products/intro.html">
 </HEAD>

 <BODY>
   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
 </BODY>
</HTML>

the relative URI "../cages/birds.gif" would resolve to:

http://www.aviary.com/cages/birds.gif

Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4 .

推荐阅读:

关于html - 有相对于​​ root 的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5559578/

相关文章:

javascript - 使用 colspan 或 rowspan 的 html 表格选择

css - 流宽 HTML5 视频不能在 iPad 或 iPhone 上运行?

JavaScript 函数默认参数无法正常工作

javascript - IE 中的 top.document.location.href 属性行为(8/9)

javascript - location.href + 指定搜索参数

除非使用 setTimeout(),否则 JavaScript 重定向 (location.href) 会破坏后退按钮

facebook - 个性化视频/Facebook 应用程序 - 最好的方法是什么?

javascript - Angular.js - 使用 $location 服务创建 url

apache - document.location.href 中的特殊字符

html - CSS - 将div对齐到文本框的右侧