重设根目录 <base>
<base> 是 HTML 里“重设根目录”的元素,该元素并不会在页面里显示,主要作用可以设定“相对路径的根目录”,这篇教学会介绍 <base> 重设根目录元素。
认识 <base>
<base> 是 HTML 里里“重设根目录”的元素,该元素会放在 HTML <head> 元素里,主要作用可以设定“相对路径的根目录”,一个网页只会有一个 <base>。
<base>属于“空元素”,只需要“起始标签”。
以下方的 HTML 为例,如果没有加入 <base>,则相对路径是以“根目录”为出发点,如果设定“/”等同没有放入 <base>。
<!DOCTYPE html>
<html>
<head>
<title>oxxo</title>
</head>
<body>
<!-- 假設根目錄為 https://www.oxxostudio.tw -->
<a href="apple.html">apple</a>
<!-- 實際連結網址為:https://www.oxxostudio.tw/apple.html -->
<br>
<a href="banana.html">banana</a>
<!-- 實際連結網址為:https://www.oxxostudio.tw/banana.html -->
</body>
</html>
如果加入 <base>,则相对路径以 <base> 里定义的 href 为出发点。
<!DOCTYPE html>
<html>
<head>
<title>OXXOSTUDIO</title>
<!-- 修改 base 的 href -->
<base href="/ok/test/">
</head>
<body>
<!-- 假設根目錄為 https://www.oxxostudio.tw -->
<a href="apple.html">apple</a>
<!-- 實際連結網址為:https://www.oxxostudio.tw/ok/test/apple.html -->
<br>
<a href="banana.html">banana</a>
<!-- 實際連結網址為:https://www.oxxostudio.tw/ok/test/banana.html -->
<br>
<a href="/orange.html">orange</a>
<!-- 因為 /orange.html 的寫法是指向根目錄 -->
<!-- 實際連結網址為:https://www.oxxostudio.tw/orange.html -->
</body>
</html>
如果 <base> 的 herf 设定为“绝对路径”( 某个网址 ),则根目录就会转换成该网址。
<!DOCTYPE html>
<html>
<head>
<title>OXXOSTUDIO</title>
<base href="https://www.google.com/test/ok/">
</head>
<body>
<!-- 假設根目錄為 https://www.oxxostudio.tw -->
<a href="apple.html">apple</a>
<!-- 實際連結網址為:https://www.google.com/test/ok/apple.html -->
<br>
<a href="banana.html">banana</a>
<!-- 實際連結網址為:https://www.google.com/test/ok/banana.html -->
<br>
<a href="/orange.html">orange</a>
<!-- 因為 /orange.html 的寫法是指向根目錄 -->
<!-- 實際連結網址為:https://www.google.com/orange.html -->
</body>
</html>
<base> 的 target 属性
<base> 除了 href 的必要属性外,也可以设定 target 属性,target 属性等同于 <a> 的 target,只要设定了 <base> 的 target,则页面中所有 <a> 的默认 target 都会跟着改变 ( 除非有额外设定 target )。
<!DOCTYPE html>
<html>
<head>
<title>OXXOSTUDIO</title>
<base href="/" target="_blank">
</head>
<body>
<a href="https://www.google.com">Google ( 開新視窗 )</a>
<br>
<a href="https://www.google.com" target="_top">Google ( 原視窗 )</a>
</body>
</html>
微信扫码关注
抖音扫码关注