被fancybox坑的心路历程

  今天项目中需要使用fancybox来展示图片,但是使用中发现fancybox没起作用,点击图片直接刷新了页面!

  fancybox的原理是通过给a标签绑定事件,使得a标签不在是直接跳转链接,而是把链接中的图片请求到一个js容器当中。

  fancybox需要初始化,类似如下

 1 $('.fancybox').fancybox({
 2     'autoSize' : true,
 3     'autoHeight' : true,
 4     'autoWidth' : true,
 5     'autoResize' : true,
 6     'autoCenter' : true,
 7     'scrolling' : 'no',
 8     'arrows' : true,
 9     'closeBtn' : true,
10     'mouseWheel' : false,
11     'modal' : false,
12     'loop' : false,
13     'playSpeed' : 500,
14     'helpers' : {
15         'title' : {'type' : 'float'},
16         'buttons' : {},
17         'overlay' : {'closeClick' : false}
18     },
19     'afterLoad' : function() {
20         this.title = 'Image ' + (this.index + 1) + ' of '
21             + this.group.length + (this.title ? ' - ' + this.title : '');
22     }
23 });

尝试将fancybox初始化函数在页面加载后执行,失败!

  一般,我们在页面初始化时执行这个初始化操作。但是项目中的图片数据时使用异步加载的,因此在图片加载完后,新请求过来打到dom上的图片外a标签并没有被fancybox初始化,因此a标签还是默认跳转url。

尝试将fancybox初始化函数在ajax请求success最后段执行,失败!

  查资料说在ajax的success默认执行上述代码,想想也是正确的,但是我的项目ajax请求得到的数据并不是一堆图片,而是一堆图片的url,当ajax的success执行完成之后,其实ajax得到的图片url才真正的开始通过img标签进行资源请求!

  放到success后也不能在图片加载完后执行fancybox初始化,这可怎么办?

尝试将fancybox初始化函数在success最后的setTimeout中延时执行,失败!

  无奈,只能在ajax的success最后的地方使用setTimeout,延时执行初始化fancybox的代码。结果还是跳转url了。

 1 function initFancybox() {
 2     setTimeout(function() {
 3         console.log($(".fancybox").length);
 4         $('.fancybox').fancybox({
 5             'autoSize' : true,
 6             'autoHeight' : true,
 7             'autoWidth' : true,
 8             'autoResize' : true,
 9             'autoCenter' : true,
10             'scrolling' : 'no',
11             'arrows' : true,
12             'closeBtn' : true,
13             'mouseWheel' : false,
14             'modal' : false,
15             'loop' : false,
16             'playSpeed' : 500,
17             'helpers' : {
18                 'title' : {'type' : 'float'},
19                 'buttons' : {},
20                 'overlay' : {'closeClick' : false}
21             },
22             'afterLoad' : function() {
23                 this.title = 'Image ' + (this.index + 1) + ' of '
24                     + this.group.length + (this.title ? ' - ' + this.title : '');
25             }
26         });
27     }, 500);
28 }

  而且没有任何征兆,控制台也正常输出了8,获取到了8个.fancybox元素,说明初始化是在图片加载之后执行的,应该没有问题啊?!

调程序,不拿出点侦探破案的劲头真的写不出程序!

通过录屏抓拍,发现从点击图片外a标签到改变url跳转到图片页中间,控制台报了错!!!

  咔嚓!这时什么鬼,搜索也搜不到资料。

  好,跟踪代码!不就是fancybox的232行嘛!

  全局搜索forbidFancybox,果然在整个fancybox的js中搜不到,好!在我的js中添加这个变量!

自己添加forbidFancybox变量

  再次请求,成功!

  我的天啊,fancybox查看图片框架竟然有这么个bug!未定义的变量不能使用都不知道吗?一群垃圾码农造的框架!

猜你喜欢

转载自www.cnblogs.com/guanghe/p/10609543.html