陈同学
微服务
Accelerator
About
# 5行代码为你的博客引入fancybox > fancybox [官网](http://fancyapps.com/fancybox/3/)、[github](https://github.com/fancyapps/fancybox) > 官网介绍:JavaScript lightbox library for presenting various types of media. Responsive, touch-enabled and customizable ## 引入目的&感谢 * **引入fancybox目的**:解决移动端访问博客文章时,图片无法放大影响阅读体验问题。 * **感谢**:超级感谢 [张帆](https://since1986.github.io) 反馈手机端访问文章时图片无法放大,影响阅读的问题,同时推荐了 [fancybox](http://fancyapps.com/fancybox/3/) 这个组件来解决这个问题。 ## fancybox官方Demo 官方Demo code很简单,将需要处理的 **img** 标签放到一个有 `data-fancybox="gallery"` 属性的 **a** 标签中即可,*href* 属性配置成放大后的图片。 ```javascript <a data-fancybox="gallery" href="big_1.jpg"> <img src="small_1.jpg"> </a> ``` ## 5行代码集成到博客 > 自行引入对应的css/js 实现思路与方式非常简单:动态为所有 **img** 标签添加一个父元素即可,有效代码就 **5** 行 ```javascript // 集成fancybox, 为所有img元素添加父元素 $("img").each(function () { // $(this).attr("data-fancybox", "gallery"); 直接给img添加data-fancybox会导致点击图片后图片消失 var element = document.createElement("a"); $(element).attr("data-fancybox", "gallery"); $(element).attr("href", $(this).attr("src")); $(this).wrap(element); }); ``` 下面是手机上访问文章 [Mysql thread 与 OS thread](https://chenyongjun.vip/articles/45) 时放大其中一张图片的效果。 ![](https://blog-1256695615.cos.ap-shanghai.myqcloud.com/2018/06/17/7e2b07a8078b45a0a698fd3c2e7f4386.png) 我的博客使用 [Editor.md](https://pandao.github.io/editor.md/) 作为markdown编辑器,在展示页面时,当editor.md渲染完html页面后,再使用上述代码动态处理 **img** 元素即可。
本文由
cyj
创作,可自由转载、引用,但需署名作者且注明文章出处。
文章标题:
5行代码为你的博客引入fancybox
文章链接:
https://chenyongjun.vip/articles/46
扫码或搜索 cyjrun 关注微信公众号, 结伴学习, 一起努力