如何在HTML中正确引用本地资源?

2023-11-23

事实证明,引用本地资源可能是一些人的摩擦点。我正在寻找本地资源引用的规范答案及其含义。

拿这些例子来说,这些参考路径有什么区别呢?

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

  • 前导斜杠告诉浏览器从根目录开始。
  • 如果没有前导斜杠,则表示是从当前目录引用。
  • 如果您在前导斜杠之前添加两个点,则意味着您正在引用当前目录的父目录。

采用以下文件夹结构

demo folder structure

notice:

  • 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/

这将是你的输出

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在HTML中正确引用本地资源? 的相关文章