jquery fancybox插件

1. 介绍

fancyBox 是一个 JavaScript 库,它以优雅的方式展示图片,视频和一些 html 内容。它包含你所期望的一切特性 —— 支持触屏,响应式和高度自定义。

1.1 依赖

推荐 jQuery 3+,但是 fancyBox 仍支持 jQery 1.9.1+ 和 jQuery 2+ 。

注意

如果你在图片缩放时遇到了问题,请升级 jQuery 到最近版本(至少v3.2.1)。

1.2 兼容

fancyBox 支持触屏操作,而且支持缩放等手势操作。在移动端和PC端上都十分合适。

fancyBox 已经在下列浏览器中测试:

Chrome
firefox
IE10/11
Edge
IOS Safari
Nexus 7 Chrome

2. 配置

可以在 html 文档中引入.css和.js来使用fancyBox,确保在这之前引入了 jQuery 库。下面是使用fancyBox的一个基本的HTML模板:

<!DOCTYPE html>

<html>

<head>
<meta charset="utf-8">
<title>My page</title>

 
  1. <!-- CSS -->
  2. <link rel="stylesheet" type="text/css" href="jquery.fancybox.min.css">

</head>

<body>

 
  1. <!-- Your HTML content goes here -->
  2.  
  3. <!-- JS -->
  4. <script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
  5. <script src="jquery.fancybox.min.js"></script>

</body>
</html>
复制代码
注意

要先引入jQuery
如果页面中已经引入过jQuery,不能再次引入
不要同时引入 fancybox.js 和 fancybox.min.js
一些方法(ajax,iframes 等)必须在一个web服务器上才可以正常运行,在浏览器打开一个本地文件是无法正常工作的

2.1 下载fancyBox

可以在 GIthub 下载最新的版本。

或者直接引用 cdnjs —cdnjs.com/libraries/f…。

2.2 包管理工具

fancyBox 还可以通多 npm 和 Bower安装。

NPM

npm install @fancyapps/fancybox —save

Bower

bower install fancybox —save
复制代码

3. 使用

3.1 使用 data 属性初始化

最基本的用法是通过添加 data-fancybox 属性到一个超链接标签。标题可以通过 data-capiton 添加。例如:

<a href="image.jpg" data-fancybox data-caption="My caption">
<img src="thumbnail.jpg" alt="" />
</a>
复制代码
在 CodePen 上查看例子

这种方式使用默认的配置,可以查看选项进行自定义配置,或者使用data-options属性。

3.2 使用 JavaScript 初始化

使用 jQuery 选择器选择一个元素,然后调用fancybox方法:

<script type="text/javascript">
$(“[data-fancybox]”).fancybox({
// Options will go here
});
</script>
复制代码
在 CodePen 上查看例子

使用这种方式,只有被选中的元素才可以触发点击事件。

为了可以现在或之后存在的元素都可以触发点击事件,使用selector选项。例如:

$().fancybox({
selector : ‘[data-fancybox=”images”]’,
loop : true
});
复制代码
在 CodePen 上查看例子

3.3 手动调用 fancyBox

fancyBox 允许使用 JavaScrip t以任意形式触发,因此不必需要通过某一个元素触发。下面例子为展示一段简单的信息:

$.fancybox.open(‘<div class="message"><h2>Hello!</h2><p>You are awesome!</p></div>‘);
复制代码
在 CodePen 上查看例子

通过 API 查看更多的信息和例子。

3.4 分组

如果你有一组元素,组内元素使用相同的 data-fancybox 值就可以组成一个相册。不同的组应该使用不同的属性值加以区分。

<a href="image_1.jpg" data-fancybox="group" data-caption="Caption #1">
<img src="thumbnail_1.jpg" alt="" />
</a>

<a href="image_2.jpg" data-fancybox="group" data-caption="Caption #2">
<img src="thumbnail_2.jpg" alt="" />
</a>
复制代码
在 CodePen 上查看例子

注意

fancyBox根据给定的url自己尝试检测内容的类型。如果无法检测,该类型可以使用data-type属性手动添加。

<a href="images.php?id=123" data-type="image" data-caption="Caption">
Show image
</a>
复制代码

4. 媒体类型

4.1 图片

使用 fancyBox 的标准做法是用小尺寸的图片链接到大尺寸图片:

<a href="image.jpg" data-fancybox="images" data-caption="My caption">
<img src="thumbnail.jpg" alt="" />
</a>
复制代码
在 CodePen 上查看例子

默认情况下,fancyBox 会在一张图片展示前进行预加载。你可以选择立即显示图片,这样当加载完成后会马上渲染和显示完整尺寸的图片。不过,以下属性是必须添加的:

data-width - 图片的完整宽度
data-height - 图片的完整高度
<a href="image.jpg" data-fancybox="images" data-width="2048" data-height="1365">
<img src="thumbnail.jpg" />
</a>
复制代码
在 CodePen 上查看例子

fancyBox 支持 scrset,它的作用是根据不同的可视区域显示不同尺寸的图片。你可以使用这个属性来减少移动端用户的下载时间。例如:

<a href="medium.jpg" data-fancybox="images" data-srcset="large.jpg 1600w, medium.jpg 1200w, small.jpg 640w">
<img src="thumbnail.jpg" />
</a>
复制代码
在 CodePen 上查看例子

fancyBox 还支持禁止右键下载来保护图片。当然这无法阻止那些下定决心下载的用户,但是可以让大多数想要盗取你文件的用户打消这个念头。

$(‘[data-fancybox]’).fancybox({
protect: true
})
复制代码
在 CodePen 上查看例子

4.2 行内 HTML

对于行内元素,你需要创建一个隐藏的元素并添加独特的 id 属性:

<div style="display: none;" id="hidden-content">
<h2>Hello</h2>
<p>You are awesome.</p>
</div>
复制代码
然后只需要创建一个带有 data-src 属性的超链接,该属性值匹配之前隐藏元素的id(优先使用# ):

<a data-fancybox data-src="#hidden-content" href="javascript:;">
Trigger the fancyBox
</a>
复制代码
在 CodePen 上查看例子

这段代码会产生一个关闭按钮(如果你没有通过 smallBtn: false 禁用的话),这个按钮只设置了居中。因此你可以很轻松地通过css来自定义样式。

4.3 Ajax

想要通过 Ajax 加载内容,需要在超链接添加 data-type=”ajax” 属性:

<a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" href="javascript:;">
AJAX content
</a>
复制代码
在 CodePen 上查看例子

另外,可以使用 data-filter 属性定义一个选择器,来显示响应的一部分。这个选择器需要是一个合法的 jQuery 选择器:

<a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" data-filter="#two" href="javascript:;">
AJAX content
</a>
复制代码
在 CodePen 上查看例子

4.4 Iframe

如果内容可以展示在页面,并且放在 iframe 中不会被脚本或者安全策略禁止,它就可以在 fancyBox 中展示:

<a data-fancybox data-type="iframe" data-src="http://codepen.io/fancyapps/full/jyEGGG/" href="javascript:;">
Webpage
</a>

<a data-fancybox data-type="iframe" data-src="https://mozilla.github.io/pdf.js/web/viewer.html" href="javascript:;">
Sample PDF
</a>
复制代码
在 CodePen 上查看例子

如果嵌入了 iframe,可以从父容器中访问和控制 fancyBox:

// 根据内容调整 iframe 的高度
parent.jQuery.fancybox.getInstance().update();

// 关闭当前的 fancyBox 实例
parent.jQuery.fancybox.getInstance().close();
复制代码
Iframe 尺寸可以通多 CSS 调整:

.fancybox-slide—iframe .fancybox-content {
width : 800px;
height : 600px;
max-width : 80%;
max-height : 80%;
margin: 0;
}
复制代码
如果需要的话,CSS 样式可以被 JS 覆盖:

$(“[data-fancybox]”).fancybox({
iframe : {
css : {
width : ‘600px’
}
}
});
复制代码
如果你没有禁止 iframe 的预加载(使用preload),那么fancyBox会尝试计算内容的尺寸,并且会根据内容来调整 iframe 的宽高。注意,这依赖于同源策略,因此会有一些限制。

下面这个例子禁止了 iframe 的预加载,并且用取消按钮代替了工具栏。

$(‘[data-fancybox]’).fancybox({
toolbar : false,
smallBtn : true,
iframe : {
preload : false
}
})
复制代码
在 CodePen 上查看例子

5. 嵌入

支持的网站可以展示在 fancyBox 中,只需要提供页面的地址即可:

<a data-fancybox href="https://www.youtube.com/watch?v=_sI_Ps7JSEk">
YouTube video
</a>

<a data-fancybox href="https://vimeo.com/191947042">
Vimeo video
</a>

<a data-fancybox href="https://www.google.com/maps/search/Empire+State+Building/">
Google Map
</a>

<a data-fancybox href="https://www.instagram.com/p/BNXYW8-goPI/?taken-by=jamesrelfdyer" data-caption="<span title="Edited">balloon rides at dawn ✨?<br>was such a magical experience floating over napa valley as the golden light hit the hills.<br><a href="https://www.instagram.com/jamesrelfdyer/">@jamesrelfdyer</a></span>">
Instagram photo
</a>
复制代码
在 CodePen 上查看例子

5.1 视频尺寸

通过 CSS 调整视频的显示大小:

.fancybox-slide—video .fancybox-content {
width : 800px;
height : 600px;
max-width : 80%;
max-height : 80%;
}
复制代码
在 CodePen 上查看例子

显然,你可以选择你喜欢的尺寸。部分未支持的画面比例,可以参照这个方法。

5.2 视频参数

通过 url 中的参数控制视频

<a data-fancybox href="https://www.youtube.com/watch?v=_sI_Ps7JSEk&autoplay=1&rel=0&controls=0&showinfo=0">
YouTube video - hide controls and info
</a>

<a data-fancybox href="https://vimeo.com/191947042?color=f00">
Vimeo video - custom color
</a>
复制代码
在 CodePen 上查看例子

通过 JavaScript 控制视频:

$(‘[data-fancybox]’).fancybox({
youtube : {
controls : 0,
showinfo : 0
},
vimeo : {
color : ‘f00’
}
});
复制代码
在 CodePen 上查看例子

6. 选项

默认选项值快速参考:

var defaults = {

 
  1. // 相册循环浏览
  2. loop : false,
  3.  
  4. // 图片周围的margin,如果视口(viewport)宽度小于800px则忽略
  5. margin : [44, 0],
  6.  
  7. // Horizontal space between slides
  8. gutter : 50,
  9.  
  10. // 键盘浏览
  11. keyboard : true,
  12.  
  13. // 是否在屏幕边缘显示箭头
  14. arrows : true,
  15.  
  16. // 是否显示infobar (顶部的counter and arrows)
  17. infobar : true,
  18.  
  19. // 是否显示顶部的toolbar
  20. toolbar : true,
  21.  
  22. // 控制顶部toolbar里显示的图表
  23. // 通过`btnTpl`选项的模板创建按钮,并被放置在toolbar(class="fancybox-toolbar"`的元素)中
  24. buttons : [
  25. 'slideShow',
  26. 'fullScreen',
  27. 'thumbs',
  28. 'share',
  29. //'download',
  30. //'zoom',
  31. 'close'
  32. ],
  33.  
  34. // 探测"idle"的时间(秒)
  35. idleTime : 3,
  36.  
  37. // 是否在右上角显示关闭按钮
  38. // 如果设置为'auto',遇到内容类型为html,inline,ajax时显示
  39. // Use template from `btnTpl.smallBtn` for customization
  40. smallBtn : 'auto',
  41.  
  42. // 保护文件,禁止右键下载
  43. protect : false,
  44.  
  45. // Shortcut to make content "modal" - 禁止键盘浏览,隐藏按钮等
  46. modal : false,
  47.  
  48. image : {
  49. // 预加载
  50. // 需要预定义图片的尺寸
  51. // 设置为'auto',自动在预览图中缩放
  52. preload : "auto"
  53.  
  54. },
  55.  
  56. ajax : {
  57.  
  58. // 请求 ajax 的配置
  59. settings : {
  60. // 表明请求是从模态框中发起,名字可改
  61. data : {
  62. fancybox : true
  63. }
  64. }
  65.  
  66. },
  67.  
  68. iframe : {
  69.  
  70. // Iframe 模板
  71. tpl : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen allowtransparency="true" src=""></iframe>',
  72.  
  73. // 预加载
  74. // 由于同源策略,不能加载跨域数据
  75. preload : true,
  76.  
  77. // 自定义包裹 iframe 的元素的 CSS 样式
  78. // 这样就可以自定义 iframe 的尺寸
  79. css : {},
  80.  
  81. // iframe 标签属性
  82. attr : {
  83. scrolling : 'auto'
  84. }
  85.  
  86. },
  87.  
  88. // 如果内容类型不能自动检测出来,默认值为'image'
  89. defaultType : 'image',
  90.  
  91. // 打开/关闭动画类型
  92. // 可用的值:
  93. // false - disable
  94. // "zoom" - zoom images from/to thumbnail
  95. // "fade"
  96. // "zoom-in-out"
  97. //
  98. animationEffect : "zoom",
  99.  
  100. // 打开/关闭动画使用的时间,ms
  101. animationDuration : 500,
  102.  
  103. // 图片缩放时是够改变透明度
  104. // 如果透明度为'auto',那么图片和缩略图比例不一致时透明度将会发生改变
  105. zoomOpacity : "auto",
  106.  
  107. // 滑块动画
  108. //
  109. // 可用的值:
  110. // false - disable
  111. // "fade'
  112. // "slide'
  113. // "circular'
  114. // "tube'
  115. // "zoom-in-out'
  116. // "rotate'
  117. //
  118. transitionEffect : "fade",
  119.  
  120. // 动画持续时间,ms
  121. transitionDuration : 366,
  122.  
  123. // 自定义的滑块的 class 值
  124. slideClass : '',
  125.  
  126. // 自定义的布局的 class 值
  127. baseClass : '',
  128.  
  129. // 布局的模板
  130. baseTpl :
  131. '<div class="fancybox-container" role="dialog" tabindex="-1">' +
  132. '<div class="fancybox-bg"></div>' +
  133. '<div class="fancybox-inner">' +
  134. '<div class="fancybox-infobar">' +
  135. '<span data-fancybox-index></span>&nbsp;/&nbsp;<span data-fancybox-count></span>' +
  136. '</div>' +
  137. '<div class="fancybox-toolbar">{{buttons}}</div>' +
  138. '<div class="fancybox-navigation">{{arrows}}</div>' +
  139. '<div class="fancybox-stage"></div>' +
  140. '<div class="fancybox-caption-wrap"><div class="fancybox-caption"></div></div>' +
  141. '</div>' +
  142. '</div>',
  143.  
  144. // 加载中时的模板
  145. spinnerTpl : '<div class="fancybox-loading"></div>',
  146.  
  147. // 错误时的模板
  148. errorTpl : '<div class="fancybox-error"><p>{{ERROR}}<p></div>',
  149.  
  150. btnTpl : {
  151.  
  152. download : '<a download data-fancybox-download class="fancybox-button fancybox-button--download" title="{{DOWNLOAD}}">' +
  153. '<svg viewBox="0 0 40 40">' +
  154. '<path d="M20,23 L20,8 L20,23 L13,16 L20,23 L27,16 L20,23 M26,28 L13,28 L27,28 L14,28" />' +
  155. '</svg>' +
  156. '</a>',
  157.  
  158. zoom : '<button data-fancybox-zoom class="fancybox-button fancybox-button--zoom" title="{{ZOOM}}">' +
  159. '<svg viewBox="0 0 40 40">' +
  160. '<path d="M 18,17 m-8,0 a 8,8 0 1,0 16,0 a 8,8 0 1,0 -16,0 M25,23 L31,29 L25,23" />' +
  161. '</svg>' +
  162. '</button>',
  163.  
  164. close : '<button data-fancybox-close class="fancybox-button fancybox-button--close" title="{{CLOSE}}">' +
  165. '<svg viewBox="0 0 40 40">' +
  166. '<path d="M10,10 L30,30 M30,10 L10,30" />' +
  167. '</svg>' +
  168. '</button>',
  169.  
  170. // 如果'smallBtn'没有设置为 false,默认关闭按钮将会被放置在你的 html/inline/ajax 内容中
  171. smallBtn : '<button data-fancybox-close class="fancybox-close-small" title="{{CLOSE}}"></button>',
  172.  
  173. // 箭头
  174. arrowLeft : '<button data-fancybox-prev class="fancybox-button fancybox-button--arrow_left" title="{{PREV}}">' +
  175. '<svg viewBox="0 0 40 40">' +
  176. '<path d="M10,20 L30,20 L10,20 L18,28 L10,20 L18,12 L10,20"></path>' +
  177. '</svg>' +
  178. '</button>',
  179.  
  180. arrowRight : '<button data-fancybox-next class="fancybox-button fancybox-button--arrow_right" title="{{NEXT}}">' +
  181. '<svg viewBox="0 0 40 40">' +
  182. '<path d="M30,20 L10,20 L30,20 L22,28 L30,20 L22,12 L30,20"></path>' +
  183. '</svg>' +
  184. '</button>'
  185. },
  186.  
  187. // 模态框放置在哪个节点中
  188. parentEl : 'body',
  189.  
  190.  
  191. // 焦点处理
  192. // ==============
  193.  
  194. // 打开后焦点在第一个支持焦点的元素上
  195. autoFocus : false,
  196.  
  197. // 关闭后焦点回到 active 的元素上
  198. backFocus : true,
  199.  
  200. // 不让用户焦点放在模态框外的内容中
  201. trapFocus : true,
  202.  
  203.  
  204. // 模态框配置
  205. // =======================
  206.  
  207. fullScreen : {
  208. autoStart : false,
  209. },
  210.  
  211. // 设置 `touch: false` 来禁止拖拽/手指滑动
  212. touch : {
  213. vertical : true, // 允许垂直方向拖拽
  214. momentum : true // Continue movement after releasing mouse/touch when panning
  215. },
  216.  
  217. // 手动初始化时的 hash 值,
  218. // 设为 `false` 不改变 hash
  219. hash : null,
  220.  
  221. // 自定义或者添加媒体类型
  222. // 例如:
  223. /*
  224. media : {
  225. youtube : {
  226. params : {
  227. autoplay : 0
  228. }
  229. }
  230. }
  231. */
  232. media : {},
  233.  
  234. slideShow : {
  235. autoStart : false,
  236. speed : 4000
  237. },
  238.  
  239. thumbs : {
  240. autoStart : false, // 打开的时候展示缩略图
  241. hideOnClose : true, // 关闭动画开始时隐藏缩略图轮廓
  242. parentEl : '.fancybox-container', // Container is injected into this element
  243. axis : 'y' // 垂直 (y) or 水平 (x) 滚动
  244. },
  245.  
  246. // 使用鼠标滚轮来浏览相册
  247. // 设为 'auto' - 只对图片启用
  248. wheel : 'auto',
  249.  
  250. // 毁掉函数
  251. //==========
  252.  
  253. // 更多信息请查看 API
  254. // 例如:
  255. /*
  256. afterShow: function( instance, current ) {
  257. console.info( 'Clicked element:' );
  258. console.info( current.opts.$orig );
  259. }
  260. */
  261.  
  262. onInit : $.noop, // 实例初始化完成
  263.  
  264. beforeLoad : $.noop, // 侧栏的内容正在被加载
  265. afterLoad : $.noop, // 侧栏的内容加载完成后
  266.  
  267. beforeShow : $.noop, // 打开动画开始前
  268. afterShow : $.noop, // 内容加载完成,进行动画的时候
  269.  
  270. beforeClose : $.noop, // 实例准备关闭的时候,返回 false 值取消关闭
  271. afterClose : $.noop, // 实例关闭后
  272.  
  273. onActivate : $.noop, // 实例激活的时候
  274. onDeactivate : $.noop, // 其他实例被激活的时候
  275.  
  276.  
  277. // 交互
  278. // ===========
  279.  
  280. // 使用一下选项自定义用户单击双击等事件
  281. // 每个选项可以是字符串,或者有返回值的方法
  282. //
  283. // 可用的值:
  284. // "close" - close instance
  285. // "next" - move to next gallery item
  286. // "nextOrClose" - move to next gallery item or close if gallery has only one item
  287. // "toggleControls" - show/hide controls
  288. // "zoom" - zoom image (if loaded)
  289. // false - do nothing
  290.  
  291. // 内容被点击
  292. clickContent : function( current, event ) {
  293. return current.type === 'image' ? 'zoom' : false;
  294. },
  295.  
  296. // 侧边栏被点击
  297. clickSlide : 'close',
  298.  
  299. // 点击模态框外的北京时
  300. clickOutside : 'close',
  301.  
  302. // 同之前的两个一样,只是是双击的时候
  303. dblclickContent : false,
  304. dblclickSlide : false,
  305. dblclickOutside : false,
  306.  
  307.  
  308. // 移动端事件
  309. // =============================================
  310.  
  311. mobile : {
  312. idleTime : false,
  313. margin : 0,
  314.  
  315. clickContent : function( current, event ) {
  316. return current.type === 'image' ? 'toggleControls' : false;
  317. },
  318. clickSlide : function( current, event ) {
  319. return current.type === 'image' ? 'toggleControls' : 'close';
  320. },
  321. dblclickContent : function( current, event ) {
  322. return current.type === 'image' ? 'zoom' : false;
  323. },
  324. dblclickSlide : function( current, event ) {
  325. return current.type === 'image' ? 'zoom' : false;
  326. }
  327. },
  328.  
  329.  
  330. // 国际化
  331. // ============
  332.  
  333. lang : 'en',
  334. i18n : {
  335. 'en' : {
  336. CLOSE : 'Close',
  337. NEXT : 'Next',
  338. PREV : 'Previous',
  339. ERROR : 'The requested content cannot be loaded. <br/> Please try again later.',
  340. PLAY_START : 'Start slideshow',
  341. PLAY_STOP : 'Pause slideshow',
  342. FULL_SCREEN : 'Full screen',
  343. THUMBS : 'Thumbnails',
  344. DOWNLOAD : 'Download',
  345. SHARE : 'Share',
  346. ZOOM : 'Zoom'
  347. },
  348. 'de' : {
  349. CLOSE : 'Schliessen',
  350. NEXT : 'Weiter',
  351. PREV : 'Zurück',
  352. ERROR : 'Die angeforderten Daten konnten nicht geladen werden. <br/> Bitte versuchen Sie es später nochmal.',
  353. PLAY_START : 'Diaschau starten',
  354. PLAY_STOP : 'Diaschau beenden',
  355. FULL_SCREEN : 'Vollbild',
  356. THUMBS : 'Vorschaubilder',
  357. DOWNLOAD : 'Herunterladen',
  358. SHARE : 'Teilen',
  359. ZOOM : 'Maßstab'
  360. }
  361. }

};
复制代码
通过传入 fancybox 方法一个对象来设置一个实例:

$(“[data-fancybox]”).fancybox({
thumbs : {
autoStart : true
}
});
复制代码
可以通过 $.fancybox.defaults 命名空间修改 fancyBox 的默认选项:

$.fancybox.defaults.animationEffect = “fade”;
复制代码
对于单独的元素可以通过 data-options 属性进行自定义。这个属性值要求JSON格式的对象:

<a data-fancybox data-options='{"caption" : "My caption", "src" : "https://codepen.io/about/", "type" : "iframe"}' href="javascript:;" class="btn">
Open external page
</a>
复制代码
在 CodePen 上查看例子

7. API

API 提供了一系列的方法来控制 fancyBox。这些方法帮助你扩展插件,整合到其他的 web 应用中。

7.1 核心方法

操作实例的核心方法:

// 只关闭当前 active 状态或者所有的 fancyBox 实例
$.fancybox.close( true );

// 打开 fancyBox
$.fancybox.open( items, opts, index );
复制代码
通过 jQuery 将相册中的元素变为 jQuery 对象或者包含纯对象的数组,进行更多操作如创建定义点击事件。

var $links = $(‘.fancybox’);

$links.on(‘click’, function() {

 
  1. $.fancybox.open( $links, {
  2. // 自定义内容
  3. }, $links.index( this ) );
  4.  
  5. return false;

});
复制代码
手动创建一组对象时,组内元素应该遵循以下规则:

{
src : ‘’ // 资源
type : ‘’ // 类型: image|inline|ajax|iframe|html (optional)
opts : {} // 选项 (optional)
}
复制代码
下面是一个通过 JavaScrip t打开相册的例子:

$.fancybox.open([
{
src : ‘1_b.jpg’,
opts : {
caption : ‘First caption’
}
},
{
src : ‘2_b.jpg’,
opts : {
caption : ‘Second caption’
}
}
], {
loop : false
});
复制代码
在 CodePen 上查看例子

fancyBox 允许只传一个对象。打开行内元素的例子:

$.fancybox.open({
src : ‘#hidden-content’,
type : ‘inline’,
opts : {
afterShow : function( instance, current ) {
console.info( ‘done!’ );
}
}
});
// 译者注:行内元素如下

<div id="#hidden-content">
<p>…content</p>
</div>
复制代码
在 CodePen 上查看例子

如果你想展示一些html文档(例如一段信息),你只需要使用很简单的一句语法。fancyBox 建议使用一个wrapper 包裹你的内容。

$.fancybox.open(‘<div class="message"><h2>Hello!</h2><p>You are awesome!</p></div>‘);
复制代码
在 CodePen 上查看例子

7.2 实例的方法

你需要定义一个实例来使用实例的方法。

var instance = $.fancybox.open(
// 内容和选项
);
复制代码
从当前 active 的实例中获取信息:

var instance = $.fancybox.getInstance();
复制代码
回调函数的第一个参数返回实例信息:

$(“[data-fancybox]”).fancybox({
afterShow : function( instance, current ) {
console.info( instance );
}
});
复制代码
实例可以调用以下方法:

// 跳到下一个相册元素
instance.next( duration );

//跳到上一个相册元素
instance.previous( duration );

// 调到选中的相册元素
instance.jumpTo( index, duration );

// 检测当前尺寸是否小于实际尺寸
instance.isScaledDown();

// 缩放到实际尺寸
instance.scaleToActual( x, y, duration );

// 检测尺寸是否超过父元素
instance.canPan();

// 缩放适应父元素尺寸
instance.scaleToFit( duration );

// 更新滑块的内容和位置
instance.update();

// 更新侧边栏的位置, 缩放内容来适应
instance.updateSlide( slide );

// 更新 infobar 的值, 导航按钮的状态, 和展示标题
instance.updateControls( force );

// 在侧边栏中加载自定义内容
instance.setContent( slide, content );

// 在侧边栏中加载loading效果
instance.showLoading( slide );

// 从侧边栏中去除loading效果
instance.hideLoading( slide );

// 找到和把焦点放在第一个可以放置焦点的元素
instance.focus();

// 激活当前 active 的实例,显示在最前面
instance.activate();

// 关闭实例
instance.close();
复制代码
你可以这样使用:

$.fancybox.getInstance().jumpTo(1);
复制代码
或者:

$.fancybox.getInstance(‘jumpTo’, 1);
复制代码

7.3 事件

fancyBox 支持触发以下事件:

beforeLoad : 滑块的内容加载前
afterLoad : 滑块内容加载后

beforeShow : 打开动画开始前
afterShow : 内容或者动画加载完成

beforeClose : 实例准备关闭前,染回false取消关闭
afterClose : 实例关闭后

onInit : 实例初始化完成
onActivate : 实例active状态
onDeactivate : 其他实例变为active状态
复制代码
事件可以作为一个对象的函数属性,该对象作为参数传入到 fancyBox 初始化方法中:

<script type="text/javascript">
$(“[data-fancybox]”).fancybox({
afterShow: function( instance, slide ) {

 
  1. // Tip: Each event passes useful information within the event object:
  2.  
  3. // Object containing references to interface elements
  4. // (background, buttons, caption, etc)
  5. // console.info( instance.$refs );
  6.  
  7. // Current slide options
  8. // console.info( slide.opts );
  9.  
  10. // Clicked element
  11. // console.info( slide.opts.$orig );
  12.  
  13. // Reference to DOM element of the slide
  14. // console.info( slide.$slide );
  15.  
  16. }
  17. });

</script>
复制代码
每一个回调函数接收两个参数 —— 当前的 fancyBox 实例和当前的相册对象(如果它们存在)。

fancyBox也支持触发所有的实例事件。为了防止和其他的脚本产生干扰,这些事件命名为.fb结尾。这些事件函数接收3个参数—事件(event),当前的 fancyBox 实例和当前的相册对象。

下面例子是绑定afterShow事件:

$(document).on(‘afterShow.fb’, function( e, instance, slide ) {
// Your code goes here
});
复制代码
如果你想阻止当前弹窗的关闭(例如在表单提交之后),可以使用beforeClose。只需要返回false即可:

beforeClose : function( instance, current, e ) {
if ( $(‘#my-field’).val() == ‘’ ) {
return false;
}
}
复制代码

8. 模块

fancyBox 代码被分成几个扩展核心功能的文件(模块)。你可以通过去除不必要的模块来构建你自己的 fancyBox 版本。如果需要,每一个模块有自己的.js和.css文件。

// 自定义、添加新的媒体类型
// 例如:
/
media : {
youtube : {
params : {
autoplay : 0
}
}
/
media : {},

slideShow : {
autoStart : false,
speed : 4000
},

thumbs : {
autoStart : false, // 打开时显示缩略图
hideOnClose : true, // Hide thumbnail grid when closing animation starts
parentEl : ‘.fancybox-container’, // Container is injected into this element
axis : ‘y’ // Vertical (y) or horizontal (x) scrolling
}

Example (show thumbnails on start):

复制代码
开始时展示缩略图的例子:

$(‘[data-fancybox=”images”]’).fancybox({
thumbs : {
autoStart : true
}
})
复制代码
如果你查看了 fancyBox 的实例对象,你会发现一些key的值是大写的 —— 他们关联着其他模块的对象。当然,你也会发现 fancyBox 使用和 jQuery 一直的前缀 $ 。

下面例子为如何拿到缩略图栅格元素:

$.fancybox.getInstance().Thumbs.$grid
复制代码
下面例子为如何调用切换缩略图的方法:

$.fancybox.getInstance().Thumbs.toggle();
复制代码
可使用的方法列表:

Thumbs.focus()
Thumbs.update();
Thumbs.hide();
Thumbs.show();
Thumbs.toggle();

FullScreen.request( elem );
FullScreen.exit();
FullScreen.toggle( elem );
FullScreen.isFullscreen();
FullScreen.enabled();

SlideShow.start();
SlideShow.stop();
SlideShow.toggle();
复制代码
如果你想禁止 hash 模块,使用下面代码片段(引用 JS 之后):

$.fancybox.defaults.hash = false;
复制代码

9. FAQ

1. 打开、关闭导致固定定位的元素移动

在固定定位的元素的class中加入compensate-for-scrollbar。例子为使用Bootstrap的navbar组件:

<nav class="navbar navbar-inverse navbar-fixed-top compensate-for-scrollbar">
<div class="container">
..
</div>
</nav>
复制代码
在 CodePen 上查看例子

上个例子中,脚本会测量滚动条的宽度,创建compensate-for-scrollbar样式并将宽度值复制到该样式的margin-right属性。因此,如果你的元素宽度设置为width:100%,你应该同时使用left和right定位,例如:

.navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
}
复制代码

2. 如何自定义标题

你可以使用caption选项,它接收一个函数,并且被组内的每个元素调用。例子为增加图片下载链接:

$( ‘[data-fancybox=”images”]’ ).fancybox({
caption : function( instance, item ) {
var caption = $(this).data(‘caption’) || ‘’;

 
  1. if ( item.type === 'image' ) {
  2. caption = (caption.length ? caption + '<br />' : '') + '<a href="' + item.src + '">Download image</a>' ;
  3. }
  4.  
  5. return caption;
  6. }

});
复制代码
在 CodePen 上查看例子

在标题右边增加当前图片的序号和图片总数:

$( ‘[data-fancybox=”images”]’ ).fancybox({
infobar : false,
caption : function( instance, item ) {
var caption = $(this).data(‘caption’) || ‘’;

 
  1. return ( caption.length ? caption + '<br />' : '' ) + 'Image <span data-fancybox-index></span> of <span data-fancybox-count></span>';
  2. }

});
复制代码
在 CodePen 上查看例子

在caption方法里面,this指向被点击的元素。例子为使用不同的标题:

$( ‘[data-fancybox]’ ).fancybox({
caption : function( instance, item ) {
return $(this).find(‘figcaption’).html();
}
});
复制代码
在 CodePen 上查看例子

3. 如何在tool上创建自定义按钮

创建可重复使用的按钮例子:

// 创建按钮模板
$.fancybox.defaults.btnTpl.fb = ‘<button data-fancybox-fb class="fancybox-button fancybox-button--fb" title="Facebook">‘ +
‘<svg viewBox="0 0 24 24">‘ +
‘<path d="M22.676 0H1.324C.594 0 0 .593 0 1.324v21.352C0 23.408.593 24 1.324 24h11.494v-9.294h-3.13v-3.62h3.13V8.41c0-3.1 1.894-4.785 4.66-4.785 1.324 0 2.463.097 2.795.14v3.24h-1.92c-1.5 0-1.793.722-1.793 1.772v2.31h3.584l-.465 3.63h-3.12V24h6.115c.733 0 1.325-.592 1.325-1.324V1.324C24 .594 23.408 0 22.676 0"/>‘ +
‘</svg>‘ +
‘</button>‘;

// 使用时间代理使按钮可点击
$(‘body’).on(‘click’, ‘[data-fancybox-fb]’, function() {
window.open(“https://www.facebook.com/sharer/sharer.php?u="+encodeURIComponent(window.location.href)+"&t="+encodeURIComponent(document.title), ‘’,’left=0,top=0,width=600,height=300,menubar=no,toolbar=no,resizable=yes,scrollbars=yes’);
});

// 自定义按钮
$( ‘[data-fancybox=”images”]’ ).fancybox({
buttons : [
‘fb’,
‘close’
]
});
复制代码
在 CodePen 上查看例子

4. 如何重置缩略图栅格的位置

这里没有 JS 选项去改变缩略图栅格的位置,但是 fancyBox 允许你使用 CSS 来改变每个块元素的位置或者尺寸(例如:内容区域,标题或者缩略图栅格)。这使你很自由的改变弹框窗口的外观和样式。

在 CodePen 上查看例子

5. 如何禁止touch操作

当你想内容可选择或者可点击,有两个选项:

设置touch:false完全禁止 touch 操作
添加data-selectable=”true”属性到你的 html 元素
在 CodePen 上查看例子

How to use 1. Setup Include nessesary JS files (FancyBox uses pngFix to fix IE png transparency). --------------------------- /* required */ <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.fancybox.js"></script> /* optional */ <script type="text/javascript" src="js/jquery.pngFix.js"></script> <script type="text/javascript" src="js/jquery.metadata.js"></script> -------------------------------------------- Include FancyBox CSS file. Dont forget to change image paths. -------------------------------------------- <link rel="stylesheet" href="css/fancybox.css" type="text/css" media="screen"> -------------------------------------------- 2. Add your images Add images and wrap them with a link to the zoomed version -------------------------------------------- <a href="image_big.jpg"><img src="image_small.jpg" alt=""/></a> -------------------------------------------- Optional: Use the title attribute if you want to show a caption Optional: Use the rel attribute to group images 3. Use the plugin Sample examples: -------------------------------------------- $(document).ready(function() { $("p#test1 a").fancybox(); $("p#test2 a").fancybox({ 'hideOnContentClick': true }); $("p#test3 a").fancybox({ 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'overlayShow': true }); }); ------------------------------------------- Available options hideOnContentClick Hides FancyBox when cliked on zoomed item (false by default) zoomSpeedIn Speed in miliseconds of the zooming-in animation (no animation if 0) zoomSpeedOut Speed in miliseconds of the zooming-out animation (no animation if 0) frameWidth Default width for iframed and inline content frameHeight Default height for iframed and inline content overlayShow If true, shows the overlay (false by default) overlayOpacity Opacity of overlay (from 0 to 1) itemLoadCallback Custom function to get group items (see example on this page source) Comments
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值