如何在CodeIgniter 3中给Fancybox图片弹窗添加链接?
为CodeIgniter3中Fancybox图片弹窗添加链接的实现方案
1. 修改PHP代码,新增跳转链接属性
假设你的$popup对象包含跳转链接字段link,在生成图片弹窗的<a>标签时,添加data-link属性存储目标链接:
<?php if ($this->dados_globais['popup'] && $this->router->fetch_class() == "home") { foreach ($this->dados_globais['popup'] as $popup) { if ($popup->imagem) { $img = base_url('./admin/assets/upload/popups/' . $popup->imagem); // 绑定跳转链接到data-link属性,为空则设为占位符 $targetLink = !empty($popup->link) ? $popup->link : '#'; echo '<a class="popup" data-fancybox="popups" href="' . $img . '" title="' . $popup->nome . '" data-caption="' . $popup->nome . '" data-link="' . $targetLink . '"></a>'; } else { $link = $popup->link; echo '<a class="popup" data-fancybox="popups" href="' . $link . '"></a>'; } } } ?>
2. 绑定Fancybox点击跳转事件
在页面JS脚本中,监听Fancybox弹窗的展示事件,为弹窗内的图片添加点击跳转逻辑:
// 初始化Fancybox并配置跳转行为 $('[data-fancybox="popups"]').fancybox({ afterShow: function(instance, current) { // 给弹窗图片绑定点击事件 current.$content.find('img').on('click', function() { const jumpLink = current.opts.$orig.data('link'); if (jumpLink && jumpLink !== '#') { // 新窗口打开链接,若需当前窗口跳转替换为window.location.href = jumpLink window.open(jumpLink, '_blank'); } }); }, // 可选:在弹窗标题添加可点击提示 caption: function(instance, item) { let captionText = $(this).data('caption') || ''; const jumpLink = $(this).data('link'); if (jumpLink && jumpLink !== '#') { captionText += '<br><small>点击图片跳转至链接</small>'; } return captionText; } });
3. 注意事项
- 确保
$popup->link存储的是完整URL格式(如https://xxx.com) - 若不需要新窗口跳转,将
window.open(jumpLink, '_blank')替换为window.location.href = jumpLink - 无跳转需求的弹窗,可在PHP中判断
$popup->link是否为空,为空则不添加data-link属性,JS会自动跳过处理
内容的提问来源于stack exchange,提问作者Geziel Silva da Cruz
相关产品推荐
相关产品推荐

