2013-01-23 20 views
32

事實證明,引用本地資源對某些人來說可能是一個難題。我正在尋找本地資源引用的規範答案,以及它們的含義。如何正確引用HTML中的本地資源?

拿這些例子,這些參考路徑有什麼區別?

  • <img src="myfile.png" />(沒有前導斜槓)
  • <img src="/myfile.png" />(與領先的斜線)
  • <img src="folder/myfile.png" />(無斜線/在子文件夾中)
  • <img src="/folder/myfile.png" />(帶斜線/子文件夾中)
  • <img src="../folder/myfile.png" /> (帶圓點和斜槓/在子文件夾中)
+0

在所有情況下,這些是相對於HTML文檔的基目錄,這是從該文件被加載的URL路徑。如果文檔是從網址加載的,則所有的URL都會根據該主機進行解析。絕對路徑是相對於網站根目錄而言的,相對URL是相對於它們出現的頁面的路徑。僅當頁面從本地HTML文件(通常表示爲file:// ... URL)加載時,URL纔會解析爲本地資源。 –

+0

@JimGarrison是的,這沒有考慮到在沒有Web服務器的情況下在本地計算機上加載文件的行爲。 –

回答

85
  • 前導斜槓告訴瀏覽器從根目錄開始。
  • 如果您沒有前導斜槓,則從當前目錄引用。
  • 如果在前導斜槓前添加兩個點,則意味着您正在引用當前目錄的父項。

採取下列文件夾結構

demo folder structure

通知:

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