Divi网站实现点击图片在Lightbox打开原图尺寸
需求与问题
我在Divi网站的文本块中嵌入了数百张图片,希望用户点击图片时,在Lightbox中打开原始尺寸的原图,而非当前src属性里的缩略图。手动修改每张图片的URL太耗时,现有的jQuery代码只能打开缩略图,求可行的jQuery方案。
图片URL示例
- 缩略图:
https://mydomain/wp-content/uploads/2023/01/myimage-235x300.jpg - 原图:
https://mydomain/wp-content/uploads/2023/01/myimage.jpg - 带序号的原图:
https://mydomain/wp-content/uploads/2023/01/myimage-1.jpg
当前HTML结构
<div class="dmpro_timeline_item_description"> <img decoding="async" loading="lazy" src="https://mydomain/wp-content/uploads/2023/01/myimage-235x300.jpg" width="235" height="300" class="wp-image-2129 alignnone size-medium"> <br> <em>Image caption</em> </div>
当前jQuery代码
<script> if ( jQuery('.dmpro_timeline_item_description').length > 0 ) { jQuery(".dmpro_timeline_item_description p img").each(function(i, e){ var img_src = jQuery(this).attr("src"); var img = jQuery(this).parent().html(); var new_elem = jQuery('<a style="color: inherit;" href="'+img_src+'">'+img+'</a>'); jQuery(this).parent().html(new_elem); }); } jQuery(document).ready(function($){ $(".dmpro_timeline_item_description p").magnificPopup({ delegate: 'a', type: 'image', closeOnContentClick: true, closeBtnInside: false, mainClass: 'mfp-no-margins mfp-with-zoom', gallery:{ enabled:false, }, zoom: { enabled: true, duration: 200 } }); }); </script>
解决方案
核心思路:通过正则表达式自动替换缩略图URL中的尺寸后缀,批量生成原图URL,再将其设为Lightbox的跳转目标。
修改后的jQuery代码如下:
<script> jQuery(document).ready(function($) { if ($('.dmpro_timeline_item_description').length > 0) { $(".dmpro_timeline_item_description img").each(function() { var $img = $(this); var thumbSrc = $img.attr("src"); // 替换缩略图URL中的尺寸后缀(如-235x300),得到原图URL var originalSrc = thumbSrc.replace(/-(\d+)x(\d+)\.(jpg|jpeg|png|gif|webp)$/, '.$3'); // 兼容带序号的原图(如myimage-1.jpg),若第一步未匹配则尝试移除序号后缀 if (originalSrc === thumbSrc) { originalSrc = thumbSrc.replace(/-(\d+)\.(jpg|jpeg|png|gif|webp)$/, '.$2'); } // 给图片包裹跳转链接,指向原图 $img.wrap('<a style="color: inherit;" href="' + originalSrc + '"></a>'); }); } // 初始化Magnific Popup $(".dmpro_timeline_item_description").magnificPopup({ delegate: 'a', type: 'image', closeOnContentClick: true, closeBtnInside: false, mainClass: 'mfp-no-margins mfp-with-zoom', gallery:{ enabled: false, }, zoom: { enabled: true, duration: 200 } }); }); </script>
代码说明
- URL转换逻辑:用正则匹配并移除WordPress缩略图特有的
-宽x高后缀,直接生成原图地址;额外兼容带序号的原图命名规则。 - 简化DOM操作:使用
wrap()方法直接给图片包裹链接,避免原代码中html()替换可能破坏的DOM结构。 - 统一执行时机:将所有逻辑放在
document.ready回调中,确保DOM加载完成后再执行操作。
内容的提问来源于stack exchange,提问作者Lloyd
相关产品推荐
相关产品推荐

