【问题标题】:How to properly reference local resources in HTML?如何正确引用 HTML 中的本地资源?
【发布时间】:2013-01-07 11:33:09
【问题描述】:

事实证明,引用本地资源对某些人来说可能是个难题。我正在寻找本地资源引用的规范答案,以及它们的含义。

举这些例子,这些引用路径有什么区别?

  • <img src="myfile.png" />(没有前导斜杠)
  • <img src="/myfile.png" />(带前导斜杠)
  • <img src="folder/myfile.png" />(子文件夹中没有前导斜杠/)
  • <img src="/folder/myfile.png" />(带有前导斜杠 / 在子文件夹中)
  • <img src="../folder/myfile.png" />(带有点和前导斜杠 / 在子文件夹中)

【问题讨论】:

  • 在所有情况下,这些都是相对于 HTML 文档的基本目录的路径,即加载文档的 URL。如果文档是从 Web URL 加载的,则所有 URL 都根据该主机进行解析。绝对路径是相对于站点的根目录解析的,相对 URL 是相对于它们出现的页面的路径。仅当页面是从本地 HTML 文件(通常表示为 file://... URL)加载时,URL 才会解析为本地资源。
  • @JimGarrison 是的,这没有考虑在没有网络服务器的情况下在本地计算机上加载文件的行为。

标签: html src ref


【解决方案1】:
  • 前导斜杠告诉浏览器从根目录开始。
  • 如果您没有前导斜杠,则表示您从当前目录引用。
  • 如果您在前导斜杠前添加两个点,则表示您正在引用当前目录的父目录。

采取如下文件夹结构

通知:

  • ROOT 复选标记为绿色,
  • 第二个复选标记是橙色,
  • 第三个复选标记是紫色,
  • 第四个复选标记为黄色

现在在index.html.en 文件中,您需要放置以下标记

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

现在,如果您加载位于第二个子文件夹中的 index.html.en 文件
http://example.com/subfolder/subfolder/

这将是你的输出

【讨论】:

    猜你喜欢
    • 2010-09-09
    • 1970-01-01
    • 2013-08-31
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2011-08-12
    相关资源
    最近更新 更多