在同一個視窗裡預覽圖片有許多種實作方式,本例採用最直覺的一種:點擊連結時,用 JavaScript 讀取該連結的 href,再把它寫進目標 img 的 src,同時把 title 當成說明文字顯示出來。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>同視窗切換圖片</title>
<style>
h1{position:absolute;margin-left:150px;}
ul{position:absolute;margin-top:50px;margin-left:80px;}
li{float:left;list-style:none;padding:1em;}
img{position:absolute;margin-top:100px;margin-left:100px;width:1000px;height:600px;}
p{position:absolute;margin-top:800px;margin-left:550px;}
</style>
<script>
function showCat(a){
var osrc = a.getAttribute("href");
var oimg = document.getElementById("img1");
oimg.setAttribute("src", osrc);
var op = document.getElementById("p1");
var otxt = a.getAttribute("title");
op.childNodes[0].nodeValue = otxt;
}
</script>
</head>
<body>
<h1>Cat Home</h1>
<ul>
<li><a href="img/1.jpg" title="我是白貓咪" onclick="showCat(this);return false;">白貓咪</a></li>
<li><a href="img/2.jpg" title="我是黑貓咪" onclick="showCat(this);return false;">黑貓咪</a></li>
<li><a href="img/3.jpg" title="我是花貓咪" onclick="showCat(this);return false;">花貓咪</a></li>
</ul>
<img id="img1" src="img/4.jpg" alt="貓咪"/>
<p id="p1">choose Cat Photo</p>
</body>
</html>
onclick="showCat(this);return false;" 中的 return false 是必要的,它阻止瀏覽器依 href 真的跳去該圖片,畫面才不會被導走。href 寫成圖片路徑而非 #,是為了兼顧「禁用 JavaScript 時仍能連到圖片」的降級情境。childNodes[0].nodeValue,是因為段落裡有文字節點;若改用 innerText 或 textContent 會更直觀。這個模式很適合商品縮圖、圖庫列表等場景。若要更進一步,可以加上淡入淡出動畫、上下張切換鍵盤支援,或先預載圖片避免切換時閃白。