有相对于​​root的链接?

Cli*_*ote 155 html location-href

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

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

<a href="fruits/index.html">Back to Fruits List</a>
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*mas 276

根相对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>
Run Code Online (Sandbox Code Playgroud)

编辑在答复问题,在注释中,从OP:

这样做/将使它相对于www.example.com,有没有办法指定根是什么,例如,如果我想在www.example.com/fruits/中将根作为www.example.com/fruits苹果/ apple.html?

是的,在href或者src属性中使用a /来表示URL 将使相对于根目录的路径成为可能.例如,在给定的HTML页面www.example.com/fruits/apples.html时,ahref="/vegetables/carrots.html"将链接到该页面www.example.com/vegetables/carrots.html.

base标签元素允许你指定基URI该页面(虽然base标签必须被添加到每个页面中它使用特定的基础是必要的,为了这个,我会简单地举W3的例子:

例如,给出以下BASE声明和A声明:

<!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>
Run Code Online (Sandbox Code Playgroud)

相对URI"../cages/birds.gif"将解析为:

http://www.aviary.com/cages/birds.gif
Run Code Online (Sandbox Code Playgroud)

举例来自:http://www.w3.org/TR/html401/struct/links.html#h-12.4.

建议阅读:

  • 所以做`/`将使它相对于`www.example.com`,有没有办法指定根是什么,例如,如果我希望根是`www中的`www.example.com/fruits`怎么办.example.com/fruits/apples/apple.html`? (2认同)
  • 有没有办法动态找到它?.NET 中的 ~ 之类的东西?如果在每个环境中你有不同的文件夹名称会发生​​什么? (2认同)

ami*_*t_g 20

使用

<a href="/fruits/index.html">Back to Fruits List</a>
Run Code Online (Sandbox Code Playgroud)

要么

<a href="../index.html">Back to Fruits List</a>
Run Code Online (Sandbox Code Playgroud)

  • **../path** 工作,但 **/path** 在 Expression Web 中对我不起作用,在 CSS 文件中使用它。(文件在 */Directory* 和引用 */DifferentDirectory* (2认同)

A-M*_*eed 6

如果您从ASP.NET 应用程序服务器端创建 URL ,并将您的网站部署到网站中的虚拟目录(例如 app2),即 http://www.yourwebsite.com/app2/

然后只需插入

<base href="~/" />
Run Code Online (Sandbox Code Playgroud)

就在标题标签之后。

所以每当你使用根相对例如

<a href="/Accounts/Login"/> 
Run Code Online (Sandbox Code Playgroud)

将解析为“ http://www.yourwebsite.com/app2/Accounts/Login

这样您就可以始终相对绝对地指向您的文件;)

对我来说这是最灵活的解决方案。

  • 你的回答根本行不通。“波形符斜杠”在 ASP.NET 解决方案的服务器端工作。这个问题与服务器端 ASP.NET 解决方案无关。 (4认同)