點擊鏈接時瀏覽器打開圖片而不是下載,是個常見困擾。在早期 IE 為主的環境裡,可以借一個隱藏 iframe 調用 execCommand("SaveAs") 觸發「另存為」。思路不複雜,關鍵是先把圖片裝進 iframe,等它就緒後再執行保存命令。
先寫一個普通的鏈接,並攔截默認行為:
<a href="picName.jpg" id="pic1" onclick="savepic(); return false;" style="cursor:pointer">點擊下載</a>
<script type="text/javascript">
function savepic() {
if (document.all.a1 == null) {
// 第一輪:動態插入承載圖片的 iframe
objIframe = document.createElement("IFRAME");
document.body.insertBefore(objIframe);
objIframe.outerHTML =
"<iframe name=a1 style='width:400px;height:300px' src=" +
imageName.href + "></iframe>";
// 稍作延時,等 iframe 內容加載完成
re = setTimeout("savepic()", 1);
} else {
// 第二輪:調起另存為並清理臨時節點
clearTimeout(re);
pic = window.open(imageName.href, "a1");
pic.document.execCommand("SaveAs");
document.all.a1.removeNode(true);
}
}
</script>
整個流程分兩次進入 savepic():第一次負責創建 iframe 並把目標圖片加載進去,隨後用 setTimeout 延遲一秒再次進入;第二次 iframe 已存在,於是打開同名窗口、調用 document.execCommand("SaveAs") 彈出保存對話框,最後把臨時 iframe 從 DOM 中移除。
需要提醒的是,這套方案依賴 IE 專有的 document.all、outerHTML 和 execCommand,只在舊版 IE 環境有效,在現代瀏覽器中並不可用。今天更通用的做法是服務端返回 Content-Disposition: attachment 響應頭,或使用 <a download> 屬性(同源資源),Canvas 場景則可用 toBlob() 配合 URL.createObjectURL()。本文保留該示例,是為了說明早期跨下載需求的實現思路。