最近才發現網站的燈箱(lightbox)沒有作用
不知道從什麼時候開始的
後來發現應該是圖檔的連結設定問題
備註1
不過原本的外掛(Meow Lightbox)確實也有問題
用其他外掛,或者佈景主題內建功能,只要連結目標設定成圖檔連結,就會有燈箱效果
以前在文章內加入圖檔,不用特別選擇連結方式
至少在今天之前,我都沒有這樣特別設定
現在要一個一個加連結,也不現實
所以用程式的方式來替文章內的圖檔加上a標籤
由於燈箱功能必須要有功能的觸發機制,不能只有a標籤
必須替這些新增的a標籤增加事件
測試幾個外掛之後,發覺佈景主題內建功能最簡單
因為佈景主題內建功能是使用Jquery的擴充函式Magnific-Popup
所以只要增加參數設定就可以了
備註2
是從這篇文章”Disable the Lightbox Scripts“給的靈感
因為文章是透過註銷magnific-popup來進行取消功能
測試之後,確實是使用Magnific-Popup
總結以上,需要增加的程式碼,可以分成3個部分
1.文章內圖檔增加a標籤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$(".entry-content img").each(function () { $(this).wrap(function () { //console.log($(this).attr("srcset")); var imgSS = $(this).attr("srcset").split(", "); //console.log(imgSS.length); // imgSS.length >=6 if (imgSS.length >= 6) { var imgTarget = imgSS.length - 1; var imgSSone = imgSS[imgTarget]; //console.log(imgSSone); var imgUrlOne = imgSSone.split(" ")[0]; console.log(imgUrlOne); //console.log('<a href="' + $(this).attr('src') + '" class="oceanwp-lightbox" />'); return '<a href="' + imgUrlOne + '" class="oceanwp-lightbox" />'; } else { // imgSS.length <6 //console.log($(this).attr("src")); return '<a href="' + $(this).attr("src") + '" class="oceanwp-lightbox" />'; } }); }); |
2.a標籤觸發Magnific-Popup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
if($(".oceanwp-lightbox").length>0){ $(".oceanwp-lightbox").magnificPopup({ type: "image", mainClass: "mfp-with-zoom", gallery: { enabled: true }, zoom: { enabled: !0, duration: 300, easing: "ease-in-out", opener: function(e) { return e.is("img") ? e : e.find("img") } } });} |
3.透過”程式碼片段”這個外掛加入以上程式碼
結果如下