fancyBox3 中文文档

译文永久地址:kangkai124.github.io/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><!-- CSS --><link rel="stylesheet" type="text/css" href="jquery.fancybox.min.css">
</head>
<body><!-- Your HTML content goes here --><!-- JS --><script src="//code.jquery.com/jquery-3.2.1.min.js"></script><script src="jquery.fancybox.min.js"></script>
</body>
</html>

注意

  • 要先引入jQuery
  • 如果页面中已经引入过jQuery,不能再次引入
  • 不要同时引入 fancybox.jsfancybox.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=&quot;Edited&quot;>balloon rides at dawn ✨?<br>was such a magical experience floating over napa valley as the golden light hit the hills.<br><a href=&quot;https://www.instagram.com/jamesrelfdyer/&quot;>@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&amp;autoplay=1&amp;rel=0&amp;controls=0&amp;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 = {// 相册循环浏览loop : false,// 图片周围的margin,如果视口(viewport)宽度小于800px则忽略margin : [44, 0],// Horizontal space between slidesgutter : 50,// 键盘浏览keyboard : true,// 是否在屏幕边缘显示箭头arrows : true,// 是否显示infobar (顶部的counter and arrows)infobar : true,// 是否显示顶部的toolbartoolbar : true,// 控制顶部toolbar里显示的图表// 通过`btnTpl`选项的模板创建按钮,并被放置在toolbar(class="fancybox-toolbar"`的元素)中buttons : ['slideShow','fullScreen','thumbs','share',//'download',//'zoom','close'],// 探测"idle"的时间(秒)idleTime : 3,// 是否在右上角显示关闭按钮// 如果设置为'auto',遇到内容类型为html,inline,ajax时显示// Use template from `btnTpl.smallBtn` for customizationsmallBtn : 'auto',// 保护文件,禁止右键下载protect : false,// Shortcut to make content "modal" - 禁止键盘浏览,隐藏按钮等modal : false,image : {// 预加载// 需要预定义图片的尺寸// 设置为'auto',自动在预览图中缩放preload : "auto"},ajax : {// 请求 ajax 的配置settings : {// 表明请求是从模态框中发起,名字可改data : {fancybox : true}}},iframe : {// Iframe 模板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>',// 预加载// 由于同源策略,不能加载跨域数据preload : true,// 自定义包裹 iframe 的元素的 CSS 样式// 这样就可以自定义 iframe 的尺寸css : {},// iframe 标签属性attr : {scrolling : 'auto'}},// 如果内容类型不能自动检测出来,默认值为'image'defaultType : 'image',// 打开/关闭动画类型// 可用的值://   false            - disable//   "zoom"           - zoom images from/to thumbnail//   "fade"//   "zoom-in-out"//animationEffect : "zoom",// 打开/关闭动画使用的时间,msanimationDuration : 500,// 图片缩放时是够改变透明度// 如果透明度为'auto',那么图片和缩略图比例不一致时透明度将会发生改变zoomOpacity : "auto",// 滑块动画//// 可用的值://   false            - disable//   "fade'//   "slide'//   "circular'//   "tube'//   "zoom-in-out'//   "rotate'//transitionEffect : "fade",// 动画持续时间,mstransitionDuration : 366,// 自定义的滑块的 class 值slideClass : '',// 自定义的布局的 class 值baseClass : '',// 布局的模板baseTpl  :'<div class="fancybox-container" role="dialog" tabindex="-1">' +'<div class="fancybox-bg"></div>' +'<div class="fancybox-inner">' +'<div class="fancybox-infobar">' +'<span data-fancybox-index></span>&nbsp;/&nbsp;<span data-fancybox-count></span>' +'</div>' +'<div class="fancybox-toolbar">{{buttons}}</div>' +'<div class="fancybox-navigation">{{arrows}}</div>' +'<div class="fancybox-stage"></div>' +'<div class="fancybox-caption-wrap"><div class="fancybox-caption"></div></div>' +'</div>' +'</div>',// 加载中时的模板spinnerTpl : '<div class="fancybox-loading"></div>',// 错误时的模板errorTpl : '<div class="fancybox-error"><p>{{ERROR}}<p></div>',btnTpl : {download : '<a download data-fancybox-download class="fancybox-button fancybox-button--download" title="{{DOWNLOAD}}">' +'<svg viewBox="0 0 40 40">' +'<path d="M20,23 L20,8 L20,23 L13,16 L20,23 L27,16 L20,23 M26,28 L13,28 L27,28 L14,28" />' +'</svg>' +'</a>',zoom : '<button data-fancybox-zoom class="fancybox-button fancybox-button--zoom" title="{{ZOOM}}">' +'<svg viewBox="0 0 40 40">' +'<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" />' +'</svg>' +'</button>',close : '<button data-fancybox-close class="fancybox-button fancybox-button--close" title="{{CLOSE}}">' +'<svg viewBox="0 0 40 40">' +'<path d="M10,10 L30,30 M30,10 L10,30" />' +'</svg>' +'</button>',// 如果'smallBtn'没有设置为 false,默认关闭按钮将会被放置在你的 html/inline/ajax 内容中smallBtn   : '<button data-fancybox-close class="fancybox-close-small" title="{{CLOSE}}"></button>',// 箭头arrowLeft : '<button data-fancybox-prev class="fancybox-button fancybox-button--arrow_left" title="{{PREV}}">' +'<svg viewBox="0 0 40 40">' +'<path d="M10,20 L30,20 L10,20 L18,28 L10,20 L18,12 L10,20"></path>' +'</svg>' +'</button>',arrowRight : '<button data-fancybox-next class="fancybox-button fancybox-button--arrow_right" title="{{NEXT}}">' +'<svg viewBox="0 0 40 40">' +'<path d="M30,20 L10,20 L30,20 L22,28 L30,20 L22,12 L30,20"></path>' +'</svg>' +'</button>'},// 模态框放置在哪个节点中parentEl : 'body',// 焦点处理// ==============// 打开后焦点在第一个支持焦点的元素上autoFocus : false,// 关闭后焦点回到 active 的元素上backFocus : true,// 不让用户焦点放在模态框外的内容中trapFocus : true,// 模态框配置// =======================fullScreen : {autoStart : false,},// 设置 `touch: false` 来禁止拖拽/手指滑动touch : {vertical : true,  // 允许垂直方向拖拽momentum : true   // Continue movement after releasing mouse/touch when panning},// 手动初始化时的 hash 值,// 设为 `false` 不改变 hashhash : null,// 自定义或者添加媒体类型// 例如:/*media : {youtube : {params : {autoplay : 0}}}*/media : {},slideShow : {autoStart : false,speed     : 4000},thumbs : {autoStart   : false,                  // 打开的时候展示缩略图hideOnClose : true,                   // 关闭动画开始时隐藏缩略图轮廓parentEl    : '.fancybox-container',  // Container is injected into this elementaxis        : 'y'                     // 垂直 (y) or 水平 (x) 滚动},// 使用鼠标滚轮来浏览相册// 设为 'auto' - 只对图片启用wheel : 'auto',// 毁掉函数//==========// 更多信息请查看 API// 例如:/*afterShow: function( instance, current ) {console.info( 'Clicked element:' );console.info( current.opts.$orig );}*/onInit       : $.noop,  // 实例初始化完成beforeLoad   : $.noop,  // 侧栏的内容正在被加载afterLoad    : $.noop,  // 侧栏的内容加载完成后beforeShow   : $.noop,  // 打开动画开始前afterShow    : $.noop,  // 内容加载完成,进行动画的时候beforeClose  : $.noop,  // 实例准备关闭的时候,返回 false 值取消关闭afterClose   : $.noop,  // 实例关闭后onActivate   : $.noop,  // 实例激活的时候onDeactivate : $.noop,  // 其他实例被激活的时候// 交互// ===========// 使用一下选项自定义用户单击双击等事件// 每个选项可以是字符串,或者有返回值的方法//// 可用的值://   "close"           - close instance//   "next"            - move to next gallery item//   "nextOrClose"     - move to next gallery item or close if gallery has only one item//   "toggleControls"  - show/hide controls//   "zoom"            - zoom image (if loaded)//   false             - do nothing// 内容被点击clickContent : function(current, event){return current.type === 'image' ? 'zoom' : false;},// 侧边栏被点击clickSlide : 'close',// 点击模态框外的北京时clickOutside : 'close',// 同之前的两个一样,只是是双击的时候dblclickContent : false,dblclickSlide   : false,dblclickOutside : false,// 移动端事件// =============================================mobile : {idleTime : false,margin   : 0,clickContent : function(current, event){return current.type === 'image' ? 'toggleControls' : false;},clickSlide : function(current, event){return current.type === 'image' ? 'toggleControls' : 'close';},dblclickContent : function(current, event){return current.type === 'image' ? 'zoom' : false;},dblclickSlide : function(current, event){return current.type === 'image' ? 'zoom' : false;}},// 国际化// ============lang : 'en',i18n : {'en' : {CLOSE       : 'Close',NEXT        : 'Next',PREV        : 'Previous',ERROR       : 'The requested content cannot be loaded. <br/> Please try again later.',PLAY_START  : 'Start slideshow',PLAY_STOP   : 'Pause slideshow',FULL_SCREEN : 'Full screen',THUMBS      : 'Thumbnails',DOWNLOAD    : 'Download',SHARE       : 'Share',ZOOM        : 'Zoom'},'de' : {CLOSE       : 'Schliessen',NEXT        : 'Weiter',PREV        : 'Zurück',ERROR       : 'Die angeforderten Daten konnten nicht geladen werden. <br/> Bitte versuchen Sie es später nochmal.',PLAY_START  : 'Diaschau starten',PLAY_STOP   : 'Diaschau beenden',FULL_SCREEN : 'Vollbild',THUMBS      : 'Vorschaubilder',DOWNLOAD    : 'Herunterladen',SHARE       : 'Teilen',ZOOM        : 'Maßstab'}}};

通过传入 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(){$.fancybox.open( $links, {// 自定义内容}, $links.index( this ) );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){// Tip: Each event passes useful information within the event object:// Object containing references to interface elements// (background, buttons, caption, etc)// console.info( instance.$refs );// Current slide options// console.info( slide.opts );// Clicked element// console.info( slide.opts.$orig );// Reference to DOM element of the slide// console.info( slide.$slide );}});
</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 startsparentEl    : '.fancybox-container',  // Container is injected into this elementaxis        : '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%,你应该同时使用leftright定位,例如:

.navbar {position: fixed;top: 0;left: 0;right: 0;
}

2. 如何自定义标题

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

$( '[data-fancybox="images"]' ).fancybox({caption : function(instance, item){var caption = $(this).data('caption') || '';if ( item.type === 'image' ) {caption = (caption.length ? caption + '<br />' : '') + '<a href="' + item.src + '">Download image</a>' ;}return caption;}
});

在 CodePen 上查看例子

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

$( '[data-fancybox="images"]' ).fancybox({infobar : false,caption : function(instance, item){var caption = $(this).data('caption') || '';return ( caption.length ? caption + '<br />' : '' ) + 'Image <span data-fancybox-index></span> of <span data-fancybox-count></span>';}
});

在 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 上查看例子

【翻译】fancyBox3 中文文档相关推荐

  1. 【翻译】fancyBox 3中文文档

    fancyBox3 中文文档 译文永久地址:https://kangkai124.github.io/fancybox/ 说明:本文档仅供参考,更新不及时请查看官方文档 1. 介绍 fancyBox是 ...

  2. perfect-scrollbar 一个全浏览器适用的自定义scrollbar,使用方法 中文文档

    在开发过程中为了保持界面样式的一致性,需要自定义scrollbar的样式,可是只有chrome可以定义样式,IE只能设置颜色,火狐是直接不可以设置,于是就找了这个库,它是github开源的,但没有中文 ...

  3. Apache Spark 2.2.0 中文文档 翻译活动

    为什么80%的码农都做不了架构师?>>>    Spark 2.2.0 已然发布(2017-07-11 发布) 5 天了,更新了一些新套路吧! 此版本从 Structured Str ...

  4. python中文语法提示_Python官方中文文档上线了:各种教程已汉化,不用再苦等野生翻译...

    终于,Python有官方中文文档了. 从今往后,不论是版本新变化,入门教程,语法讲解,Python模块安装指南--各种各样的手册,都可以直接看中文了. △ 不是谷歌翻译哟 你看,比起英文原版,中文的语 ...

  5. GitHub 中文文档正式发布

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试资料 中国作为全球最大的人口大国,所属开发者在 GitHub 上的占比自 ...

  6. 使用编译器——Solidity中文文档(8)

    写在前面:HiBlock区块链社区成立了翻译小组,翻译区块链相关的技术文档及资料,本文为Solidity文档翻译的第八部分<使用编译器>,特发布出来邀请solidity爱好者.开发者做公开 ...

  7. 已知bug列表——Solidity中文文档(12)

    写在前面:HiBlock区块链社区成立了翻译小组,翻译区块链相关的技术文档及资料,本文为Solidity文档翻译的第十二部分<已知bug列表>,特发布出来邀请solidity爱好者.开发者 ...

  8. Android2.2 API 中文文档系列(7) —— ImageButton

    前言 第七篇关于ImageButton的翻译在翻译工具帮助下独立完成,加了一些自己的理解甚至截图,水平有限,欢迎指正.欢迎更多译者一起参与Android API 的中文翻译行动!我的邮箱over140 ...

  9. python语言需要英语非常好吗-Python用不好英语水平不够?这里有官方中文文档你看不看...

    Python 作为世界上最好用的语言,官方支持的文档一直没有中文.小伙伴们已经习惯了原汁原味的英文文档,但如果有官方中文文档,那么查阅或理解速度都会大大提升.本文将介绍隐藏在 Python 官网的中文 ...

最新文章

  1. 现在的编译器还需要手动展开循环吗_性能 - 如果有的话,循环展开仍然有用吗?...
  2. Linux上安装MongoDB
  3. NFS 安装配置及常见问题
  4. react源代码重点难点分析
  5. iAPP(05)自习室占座
  6. 计算机网络拓跋结构,实战 | 服务端开发与计算机网络结合的完美案例
  7. Go 都在什么时候触发GC,能手动触发GC吗?
  8. pandas 数据处理进阶
  9. openstack-o版-nova安装
  10. 敏捷开发团队管理系列之四:程序与测试团队III
  11. redux,react-redux之间的关系
  12. clickhouse kafka引擎入门
  13. 常见物理性能测试仪器设备档案
  14. 低功耗技术——低功耗中使用的特殊单元
  15. Mac —— QuickTime录屏 声音小解决
  16. 苹果官方mfi认证名单_苹果入驻抖音,完成官方认证
  17. systemctl重新加载_CentOS7利用systemctl添加自定义系统服务【转】
  18. 深度学习与人类语言处理学习笔记(二)—— 变声(理论篇)
  19. 计算机公式等级评定,Excel函数如何完成学生成绩等级评定
  20. 【0day RCE】 Horde Groupware Webmail Edition RCE

热门文章

  1. 酒店怎么在抖音宣传推广?
  2. 【AI绘图学习笔记】transformer
  3. TYVJ 武器分配
  4. 2022年全球市场静脉注射用包装总体规模、主要生产商、主要地区、产品和应用细分研究报告
  5. SVN入门第三讲——SVN恢复到历史版本
  6. OTP概念及实现原理简析 安当加密
  7. δ星 丨 读书笔记 notes-《富甲美国》:顾客至上,极致性价比
  8. OLED demura技术学习part2
  9. Tomcat 8报错 SEVERE: One or more listener failed to start,如何找到更详细的错误信息
  10. tomcat html文件修改后没生效,Tomcat-页面访问时新Jsp未生效