部落格、相簿、產品列表等頁面,需將所有圖片自動包裹成連結,點擊可在新分頁開啟原圖或指定頁面。
<div id="replAll">
<img alt="" src="20140925101646722.png" /><br/>
<img alt="" src="20140919094831881.png" />
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
var targetUrl = 'https://www.example.com'; // 目標連結
// 方式一:點擊按鈕時批次包裝
$("#replAll").click(function() {
$('img').each(function() {
var $img = $(this);
// 避免重複包裝
if (!$img.parent('a').length) {
$img.wrap("<a href='" + targetUrl + "' target='_blank'></a>");
}
});
});
// 方式二:頁面載入自動包裝 (無需點擊)
// $('img').each(function() { ... });
});
</script>
$(function() {
$('img').each(function() {
var $img = $(this);
var src = $img.attr('src');
// 跳過已包裝、無 src、data URI、base64 圖片
if (!$img.parent('a').length && src && !src.startsWith('data:')) {
$img.wrap('');
}
});
});
<style>
.image-link {
cursor: zoom-in;
display: inline-block;
border: none;
text-decoration: none;
}
.image-link:hover { opacity: 0.9; }
.image-link img { display: block; } /* 消除底部間隙 */
</style>
// 排除有 .no-link 類別的圖片
$('img:not(.no-link)').each(function() { ... });
// 排除特定容器內的圖片
$('img').not('.header img, .footer img, .logo').each(function() { ... });
// 只處理特定容器
$('#content img, .article img').each(function() { ... });
document.addEventListener('DOMContentLoaded', function() {
var targetUrl = 'https://www.example.com';
var images = document.querySelectorAll('img:not([data-no-link])');
images.forEach(function(img) {
// 避免重複包裝
if (img.parentElement.tagName !== 'A') {
var link = document.createElement('a');
link.href = targetUrl;
link.target = '_blank';
link.className = 'image-link';
img.parentNode.insertBefore(link, img);
link.appendChild(img);
}
});
});
// 使用 DocumentFragment 批次操作 (原生)
var fragment = document.createDocumentFragment();
var links = [];
images.forEach(function(img) {
if (img.parentElement.tagName !== 'A') {
var link = document.createElement('a');
link.href = targetUrl;
link.target = '_blank';
link.appendChild(img); // 移動會自動從原位置移除
links.push(link);
}
});
// 一次性加入 (需重新計算位置,適合動態產生容器)
// 若在原位置包裝,直接操作即可,現代瀏覽器優化已足夠
// IntersectionObserver 延遲包裝 (圖片進入視窗時才處理)
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
wrapImage(entry.target);
observer.unobserve(entry.target);
}
});
});
document.querySelectorAll('img').forEach(function(img) { observer.observe(img); });
// 自動加上 data-lightbox 屬性供 lightbox2 等庫使用
$('img').each(function() {
var $img = $(this);
if (!$img.parent('a').length && $img.attr('src')) {
$img.wrap('');
}
});
| 問題 | 原因 | 解決 |
|---|---|---|
| 重複包裝產生巢狀 <a> | 多次執行腳本 | 檢查 $img.parent('a').length |
| SVG 圖片包裝後顯示異常 | <svg> 不支援某些 CSS | 排除 img[src$=".svg"] 或用 object 嵌入 |
| 背景圖片 (CSS background) 被誤處理 | 選擇器包含非 <img> 元素 | 嚴格用 $('img') 或 document.querySelectorAll('img') |
| 動態新增圖片未生效 | 只在載入時執行一次 | 使用事件委派或 MutationObserver 監聽 DOM 變化 |
.wrap() 是 jQuery 批次包裝元素的利器。實務上建議:頁面載入時自動處理、排除不需連結的圖片、搭配 CSS 提供視覺回饋、大量圖片考慮 IntersectionObserver 延遲處理、現代專案可改用原生 JS 減少依賴。