使用fancyBox为图片添加放大及相册功能
fancyBox是一个流行的媒体展示增强组件,可以方便为网站添加图片放大、相册浏览、视频弹出层播放等效果。使用简单支持高度自定义,兼顾触屏、响应式移动端特性,总之使用体验相当好。下面示例fancyBox的常见用法,为图片添加放大和灯箱功能。
fancyBox GitHub地址 https://github.com/fancyapps/fancybox
下载所需js和css文件引入到网页,或者使用CDN资源引入。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test Page</title> <!-- CSS --> <link rel="stylesheet" type="text/css" href="jquery.fancybox.min.css"> </head> <body> <!-- JS --> <script src="//code.jquery.com/jquery-3.2.1.min.js"></script> <script src="jquery.fancybox.min.js"></script> </body> </html>
fancyBox依赖jQuery 3+,但是也支持jQery 1.9.1+,就是有的功能效果差些。
接着在<img>标签外包裹一个<a>超链接,里面附上图片url,添加data属性绑定事件。如果只是图片放大功能,只需添加data-fancybox
属性就可以,不需带属性值。
如果带属性值,则表示这是一个相册。当有多个图片链接带了同样属性值,就视为一个相册,在图片放大时会显示上下浏览按钮。
如果要为图片添加备注文字,使用data-caption=""
属性。
以下是示例HTML结构。
<a href="image_1.jpg" data-fancybox="lightbox" data-caption="图像描述 #1"> <img src="thumbnail_1.jpg" alt="" /> </a> <a href="image_2.jpg" data-fancybox="lightbox" data-caption="图像描述 #2"> <img src="thumbnail_2.jpg" alt="" /> </a>
完成以上两步操作就可以使用了,效果如下演示。




实际使用过程中,有时不可能每个图片去手动添加。这时可以在网站后台处理,例如在网站模板文件里通过正则输出。或者前端使用JS脚本自动添加。
以下是一段演示代码,使用jQery在选定元素里自动添加<a>包裹标签。其中url地址和描述信息取自<img>属性。
$(document).ready(function() { $("img").each(function() { var currentImage = $(this); currentImage.wrap("<a href='" + currentImage.attr("src") + "' data-fancybox='lightbox' data-caption='" + currentImage.attr("alt") + "'></a>"); }); });
JS添加还有更多玩法,可以按需加载文件和执行事件,网页源码也更简洁,没有多余标签输出……
最后也建议大家看看fancyBox官方文档,里面介绍了详细功能选项,可以根据自己需求定制不同效果。
why does naltrexone cost so much now https://naltrexoneonline.confrancisyalgomas.com/
ivermectin and covid 19 treatment https://ivermectin.mlsmalta.com/
availability of hydroxychloroquine https://hhydroxychloroquine.com/
can you take vidalista daily https://vidalista40mg.mlsmalta.com/
is there generic dapoxetine https://ddapoxetine.com/
generic cialis vs generic viagra https://wisig.org/
online doctor ontario free https://buymeds.mlsmalta.com/
online doctor ontario free https://medpills.bee-rich.com/
how to write albuterol prescription https://amstyles.com/
hydroxychloroquine for covid 19 https://hydroxychloroquinee.com/
dose of cialis https://tadfil.online/
dose of cialis https://tadalafileo.online/
hydroxychloroquine sulfate tablet https://hydroxychloroquine.grassfed.us/
hydroxychloroquine sulfate tablet https://hydroxychloroquine.wisig.org/
40 mg prednisone daily https://bvsinfotech.com/
hydroxychloroquine retinopathy symptoms https://hydroxychloroquine4u.com/
how to order cialis online https://cialis.mrdgeography.com/
how to order cialis online https://cialis.confrancisyalgomas.com/
why does cialis not work https://cialis.mlsmalta.com/
why does cialis not work http://cialis.anafassia.com/