被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!未定義的變量不能使用都不知道嗎?一群垃圾碼農造的框架!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM