萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 自動為頁面所有圖片加上連結:批次包裝 wrap() 應用範例

需求場景

部落格、相簿、產品列表等頁面,需將所有圖片自動包裹成連結,點擊可在新分頁開啟原圖或指定頁面。

HTML 結構

<div id="replAll">
    <img alt="" src="20140925101646722.png" /><br/>
    <img alt="" src="20140919094831881.png" />
</div>

jQuery 核心代碼

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

進階功能:連結目標為圖片本身 (Lightbox 效果基礎)

$(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('');
        }
    });
});

CSS 搭配:滑鼠樣式提示

<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() { ... });

原生 JS 實現 (無依賴)

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); });

進階:整合 Lightbox 庫

// 自動加上 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 減少依賴。

copyright © 萬盛學電腦網 all rights reserved