介绍
开始使用fancybox,可能是世界上最受欢迎的灯箱脚本。
依赖
jQuery 3+是首选,但fancybox适用于jQuery 1.9.1+和jQuery 2+
兼容性
fancybox包括对触摸手势的支持,甚至还支持缩放手势以进行缩放。它非常适合移动和桌面浏览器。
fancybox已在以下浏览器/设备中测试过:
- 铬
- 火狐
- IE10 / 11
- 边缘
- iOS Safari
- Android 7.0平板电脑
建立
您可以通过链接.css
和
.js
文件到您的html文件来安装fancybox
。确保您还加载了jQuery库。下面是一个用作示例的基本HTML模板:
<!DOCTYPE html> <HTML> <HEAD> <meta charset =“utf-8”> <title>我的页面</ title> <! - CSS - > <link rel =“stylesheet”type =“text / css”href =“jquery.fancybox.min.css”> </ HEAD> <BODY> <! - 您的HTML内容在这里 - > <! - JS - > <script src =“// code.jquery.com/jquery-3.2.1.min.js”> </ script> <script src =“jquery.fancybox.min.js”> </ script> </ BODY> </ HTML>
下载fancybox
在GitHub上下载最新版本的fancybox
。
或者直接链接到cdnjs上的fancybox文件 -
https://cdnjs.com/libraries/fancybox。
包裹经理
nancy和Bower也提供fancybox。
# NPM
npm install @fancyapps/fancybox --save
# Bower
bower install fancybox --save
重要
- 确保在fancybox JS文件之前添加jQuery库
- 如果您的页面上已经有jQuery,则不应该第二次包含它
- 不要包含fancybox.js和fancybox.min.js文件
- 当您直接在浏览器上打开本地文件时,某些功能(ajax,iframe等)将无法运行,代码必须在Web服务器上运行
如何使用
使用数据属性进行初始化
使用fancybox的最基本方法是将data-fancybox
元素添加
到元素中。这将自动绑定将启动fancybox的click事件。使用
href
或
data-src
属性指定内容的来源。例:
<a href="image.jpg" data-fancybox data-caption="Caption for single image"> <img src =“thumbnail.jpg”alt =“”/> </A>
如果您有一组项目,则可data-fancybox
以为每个项目使用相同的属性
值来创建图库。每个组都应具有唯一值。例:
<a href="image_1.jpg" data-fancybox="gallery" data-caption="Caption #1"> <img src =“thumbnail_1.jpg”alt =“”/> </A> <a href="image_2.jpg" data-fancybox="gallery" data-caption="Caption #2"> <img src =“thumbnail_2.jpg”alt =“”/> </A>
如果选择此方法,将应用默认设置。有关如何通过更改默认值,使用属性或使用JavaScript初始化来自定义的示例,请参阅
选项部分
。
data-options
信息
有时,您有多个链接指向同一个源,并在库中创建重复项。为避免这种情况,只需使用
data-fancybox-trigger
与data-fancybox
其他链接的属性相同的
属性。(可选)使用
data-fancybox-index
attribute指定起始元素的索引:
<a data-fancybox-trigger="gallery" href="javascript:;">
<img src="thumbnail_1.jpg" alt="" />
</a>
使用JavaScript初始化
使用jQuery选择器选择元素(可以使用任何有效的选择器)并调用
fancybox
方法:
$('[data-fancybox="gallery"]').fancybox({
// Options will go here
});
信息
有时您可能需要将fancybox绑定到动态添加的元素。使用
selector
选项为现在或将来存在的元素附加单击事件侦听器。所有选定的项目将自动分组到库中。例:
$().fancybox({
selector : '.imglist a:visible'
});
与Javascript一起使用
您还可以通过编程方式打开和关闭fancybox。以下是一些示例,请访问 API部分以获取更多信息和演示。
显示简单消息:
$.fancybox.open('<div class="message"><h2>Hello!</h2><p>You are awesome!</p></div>');
显示iframed页面:
$.fancybox.open({
src : 'link-to-your-page.html',
type : 'iframe',
opts : {
afterShow : function( instance, current ) {
console.info( 'done!' );
}
}
});
重要
fancybox尝试根据给定的URL自动检测内容类型。如果无法检测到,也可以使用data-type
属性(或
type
选项)手动设置类型
。例:
<a href="images.php?id=123" data-type="image" data-caption="Caption"> 显示图片 </A>
媒体类型
fancybox旨在显示图像,视频,iframe和任何HTML内容。为方便起见,内置支持内联内容和ajax。
图片
使用fancybox的标准方法是使用许多链接到较大图像的缩略图:
<a href="image.jpg" data-fancybox="images" data-caption="My caption">
<img src="thumbnail.jpg" alt="" />
</a>
默认情况下,fancybox会在显示之前完全预加载图像。您可以选择立即显示图像。它将在接收数据时呈现并显示完整大小的图像。为此,需要一些属性:
-
data-width
- 图像的实际宽度 -
data-height
- 图像的真实高度
<a href="image.jpg" data-fancybox="images" data-width="2048" data-height="1365">
<img src="thumbnail.jpg" />
</a>
您还可以使用这些
width
和
height
属性来控制图像的大小。这可用于使图像在视网膜显示器上看起来更清晰。例:
$('[data-fancybox="images"]').fancybox({
afterLoad : function(instance, current) {
var pixelRatio = window.devicePixelRatio || 1;
if ( pixelRatio > 1.5 ) {
current.width = current.width / pixelRatio;
current.height = current.height / pixelRatio;
}
}
});
fancybox支持“srcset”,因此它可以根据视口宽度显示不同的图像。您可以使用它来改善移动用户的下载时间,并随着时间的推移节省带宽。例:
<a href="medium.jpg" data-fancybox="images" data-srcset="large.jpg 1600w, medium.jpg 1200w, small.jpg 640w">
<img src="thumbnail.jpg" />
</a>
也可以通过右键单击来保护图像免遭下载。虽然这不能保护真正确定的用户,但它应该阻止绝大多数人扯下您的文件。(可选)将水印放在图像上。
$('[data-fancybox]').fancybox({
protect: true
});
视频
只需提供页面网址,YouTube和Vimeo视频就可以与fancybox一起使用。直接链接到MP4视频或使用触发元素显示隐藏<video>
元素。
使用
data-width
和
data-height
属性来自定义视频尺寸和
data-ratio
纵横比。
<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 data-width="640" data-height="360" href="video.mp4">
Direct link to MP4 video
</a>
<a data-fancybox href="#myVideo">
HTML5 video element
</a>
<video width="640" height="320" controls id="myVideo" style="display:none;">
<source src="https://www.html5rocks.com/en/tutorials/video/basics/Chrome_ImF.mp4" type="video/mp4">
<source src="https://www.html5rocks.com/en/tutorials/video/basics/Chrome_ImF.webm" type="video/webm">
<source src="https://www.html5rocks.com/en/tutorials/video/basics/Chrome_ImF.ogv" type="video/ogg">
Your browser doesn't support HTML5 video tag.
</video>
通过网址参数控制YouTube和Vimeo视频:
<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>
通过JavaScript:
$('[data-fancybox]').fancybox({
youtube : {
controls : 0,
showinfo : 0
},
vimeo : {
color : 'f00'
}
});
IFRAME
如果您需要显示来自另一页面的内容,添加data-fancybox
和data-type="iframe"
属性您的链接。这将创建<iframe>
允许将整个Web文档嵌入模态中的元素。
<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 file
</a>
如果您尚未禁用iframe预加载(使用
preload
选项),则脚本将尝试计算内容尺寸,并将调整宽度/高度<iframe>
以适合其中的内容。请记住,由于
相同的原始政策,存在一些限制。
此示例将禁用iframe预加载,并将在iframe旁边显示小关闭按钮而不是工具栏:
$('[data-fancybox]').fancybox({
toolbar : false,
smallBtn : true,
iframe : {
preload : false
}
})
iframe维度可以通过CSS控制:
.fancybox-slide--iframe .fancybox-content {
width : 800px;
height : 600px;
max-width : 80%;
max-height : 80%;
margin: 0;
}
如果需要,JS可以覆盖这些CSS规则:
$("[data-fancybox]").fancybox({
iframe : {
css : {
width : '600px'
}
}
});
如何从iframe内部访问和控制父窗口中的fancybox:
// Close current fancybox instance
parent.jQuery.fancybox.getInstance().close();
// Adjust iframe height according to the contents
parent.jQuery.fancybox.getInstance().update();
排队
fancybox可用于在页面上显示任何HTML元素。首先,创建一个具有唯一ID的隐藏元素:
<div style="display: none;" id="hidden-content">
<h2>Hello</h2>
<p>You are awesome.</p>
</div>
然后,只需创建一个链接,其
data-src
属性与您要打开的元素的ID匹配(前面有一个井号(#);在本例中 - #hidden-content
):
<a data-fancybox data-src="#hidden-content" href="javascript:;">
Trigger the fancybox
</a>
该脚本将附加小关闭按钮(如果您没有禁用
smallBtn:false
)并且除了居中之外不会应用任何样式。因此,您可以使用CSS轻松设置自定义尺寸。
信息如果需要,您可以通过在CodePen上添加额外的包装元素和一些CSS 视图演示来使您的元素(以及类似的任何其他html内容)可滚动 。
阿贾克斯
要通过AJAX加载内容,您需要为data-type="ajax"
链接添加
属性:
<a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" href="javascript:;">
AJAX content
</a>
此外,可以使用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>
选项
源中定义的所有默认选项的快速参考:
var defaults = { // Close existing modals // Set this to false if you do not need to stack multiple instances closeExisting: false, // Enable infinite gallery navigation loop: false, // Horizontal space between slides gutter: 50, // Enable keyboard navigation keyboard: true, // Should allow caption to overlap the content preventCaptionOverlap: true, // Should display navigation arrows at the screen edges arrows: true, // Should display counter at the top left corner infobar: true, // Should display close button (using `btnTpl.smallBtn` template) over the content // Can be true, false, "auto" // If "auto" - will be automatically enabled for "html", "inline" or "ajax" items smallBtn: "auto", // Should display toolbar (buttons at the top) // Can be true, false, "auto" // If "auto" - will be automatically hidden if "smallBtn" is enabled toolbar: "auto", // What buttons should appear in the top right corner. // Buttons will be created using templates from `btnTpl` option // and they will be placed into toolbar (class="fancybox-toolbar"` element) buttons: [ "zoom", //"share", "slideShow", //"fullScreen", //"download", "thumbs", "close" ], // Detect "idle" time in seconds idleTime: 3, // Disable right-click and use simple image protection for images protect: false, // Shortcut to make content "modal" - disable keyboard navigtion, hide buttons, etc modal: false, image: { // Wait for images to load before displaying // true - wait for image to load and then display; // false - display thumbnail and load the full-sized image over top, // requires predefined image dimensions (`data-width` and `data-height` attributes) preload: false }, ajax: { // Object containing settings for ajax request settings: { // This helps to indicate that request comes from the modal // Feel free to change naming data: { fancybox: true } } }, iframe: { // Iframe template tpl: '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" allowfullscreen allow="autoplay; fullscreen" src=""></iframe>', // Preload iframe before displaying it // This allows to calculate iframe content width and height // (note: Due to "Same Origin Policy", you can't get cross domain data). preload: true, // Custom CSS styling for iframe wrapping element // You can use this to set custom iframe dimensions css: {}, // Iframe tag attributes attr: { scrolling: "auto" } }, // For HTML5 video only video: { tpl: '<video class="fancybox-video" controls controlsList="nodownload" poster="{{poster}}">' + '<source src="{{src}}" type="{{format}}" />' + 'Sorry, your browser doesn\'t support embedded videos, <a href="{{src}}">download</a> and watch with your favorite video player!' + "</video>", format: "", // custom video format autoStart: true }, // Default content type if cannot be detected automatically defaultType: "image", // Open/close animation type // Possible values: // false - disable // "zoom" - zoom images from/to thumbnail // "fade" // "zoom-in-out" // animationEffect: "zoom", // Duration in ms for open/close animation animationDuration: 366, // Should image change opacity while zooming // If opacity is "auto", then opacity will be changed if image and thumbnail have different aspect ratios zoomOpacity: "auto", // Transition effect between slides // // Possible values: // false - disable // "fade' // "slide' // "circular' // "tube' // "zoom-in-out' // "rotate' // transitionEffect: "fade", // Duration in ms for transition animation transitionDuration: 366, // Custom CSS class for slide element slideClass: "", // Custom CSS class for layout baseClass: "", // Base template for layout 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> / <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"></div>' + "</div>" + "</div>", // Loading indicator template spinnerTpl: '<div class="fancybox-loading"></div>', // Error message template errorTpl: '<div class="fancybox-error"><p>{{ERROR}}</p></div>', btnTpl: { download: '<a download data-fancybox-download class="fancybox-button fancybox-button--download" title="{{DOWNLOAD}}" href="javascript:;">' + '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18.62 17.09V19H5.38v-1.91zm-2.97-6.96L17 11.45l-5 4.87-5-4.87 1.36-1.32 2.68 2.64V5h1.92v7.77z"/></svg>' + "</a>", zoom: '<button data-fancybox-zoom class="fancybox-button fancybox-button--zoom" title="{{ZOOM}}">' + '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18.7 17.3l-3-3a5.9 5.9 0 0 0-.6-7.6 5.9 5.9 0 0 0-8.4 0 5.9 5.9 0 0 0 0 8.4 5.9 5.9 0 0 0 7.7.7l3 3a1 1 0 0 0 1.3 0c.4-.5.4-1 0-1.5zM8.1 13.8a4 4 0 0 1 0-5.7 4 4 0 0 1 5.7 0 4 4 0 0 1 0 5.7 4 4 0 0 1-5.7 0z"/></svg>' + "</button>", close: '<button data-fancybox-close class="fancybox-button fancybox-button--close" title="{{CLOSE}}">' + '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 10.6L6.6 5.2 5.2 6.6l5.4 5.4-5.4 5.4 1.4 1.4 5.4-5.4 5.4 5.4 1.4-1.4-5.4-5.4 5.4-5.4-1.4-1.4-5.4 5.4z"/></svg>' + "</button>", // Arrows arrowLeft: '<button data-fancybox-prev class="fancybox-button fancybox-button--arrow_left" title="{{PREV}}">' + '<div><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M11.28 15.7l-1.34 1.37L5 12l4.94-5.07 1.34 1.38-2.68 2.72H19v1.94H8.6z"/></svg></div>' + "</button>", arrowRight: '<button data-fancybox-next class="fancybox-button fancybox-button--arrow_right" title="{{NEXT}}">' + '<div><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.4 12.97l-2.68 2.72 1.34 1.38L19 12l-4.94-5.07-1.34 1.38 2.68 2.72H5v1.94z"/></svg></div>' + "</button>", // This small close button will be appended to your html/inline/ajax content by default, // if "smallBtn" option is not set to false smallBtn: '<button type="button" data-fancybox-close class="fancybox-button fancybox-close-small" title="{{CLOSE}}">' + '<svg xmlns="http://www.w3.org/2000/svg" version="1" viewBox="0 0 24 24"><path d="M13 12l5-5-1-1-5 5-5-5-1 1 5 5-5 5 1 1 5-5 5 5 1-1z"/></svg>' + "</button>" }, // Container is injected into this element parentEl: "body", // Hide browser vertical scrollbars; use at your own risk hideScrollbar: true, // Focus handling // ============== // Try to focus on the first focusable element after opening autoFocus: true, // Put focus back to active element after closing backFocus: true, // Do not let user to focus on element outside modal content trapFocus: true, // Module specific options // ======================= fullScreen: { autoStart: false }, // Set `touch: false` to disable panning/swiping touch: { vertical: true, // Allow to drag content vertically momentum: true // Continue movement after releasing mouse/touch when panning }, // Hash value when initializing manually, // set `false` to disable hash change hash: null, // Customize or add new media types // Example: /* media : { youtube : { params : { autoplay : 0 } } } */ media: {}, slideShow: { autoStart: false, speed: 3000 }, thumbs: { autoStart: false, // Display thumbnails on opening 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 }, // Use mousewheel to navigate gallery // If 'auto' - enabled for images only wheel: "auto", // Callbacks //========== // See Documentation/API/Events for more information // Example: /* afterShow: function( instance, current ) { console.info( 'Clicked element:' ); console.info( current.opts.$orig ); } */ onInit: $.noop, // When instance has been initialized beforeLoad: $.noop, // Before the content of a slide is being loaded afterLoad: $.noop, // When the content of a slide is done loading beforeShow: $.noop, // Before open animation starts afterShow: $.noop, // When content is done loading and animating beforeClose: $.noop, // Before the instance attempts to close. Return false to cancel the close. afterClose: $.noop, // After instance has been closed onActivate: $.noop, // When instance is brought to front onDeactivate: $.noop, // When other instance has been activated // Interaction // =========== // Use options below to customize taken action when user clicks or double clicks on the fancyBox area, // each option can be string or method that returns value. // // Possible values: // "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 // Clicked on the content clickContent: function(current, event) { return current.type === "image" ? "zoom" : false; }, // Clicked on the slide clickSlide: "close", // Clicked on the background (backdrop) element; // if you have not changed the layout, then most likely you need to use `clickSlide` option clickOutside: "close", // Same as previous two, but for double click dblclickContent: false, dblclickSlide: false, dblclickOutside: false, // Custom options when mobile device is detected // ============================================= mobile: { preventCaptionOverlap: false, idleTime: false, 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; } }, // Internationalization // ==================== 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="gallery"]').fancybox({
thumbs : {
autoStart : true
}
});
插件选项/默认值在$.fancybox.defaults
命名空间中公开,
因此您可以轻松地全局调整它们:
$.fancybox.defaults.animationEffect = "fade";
可以通过向data-options
元素添加属性来设置每个元素的自定义选项
。此属性应包含格式正确的JSON对象(请记住,字符串应包含在双引号中)。
也可以使用所选选项的参数化名称快速设置任何
选项,例如,
animationEffect
将data-animation-effect
:
<a data-fancybox data-options='{"caption" : "My caption", "src" : "https://codepen.io/about/", "type" : "iframe"}' href="javascript:;" class="btn btn-primary">
Example #1
</a>
<a data-fancybox data-animation-effect="false" href="https://source.unsplash.com/0JYgd2QuMfw/1500x1000" class="btn btn-primary">
Example #2
</a>
API
fancybox API提供了几种控制fancybox的方法。这使您能够扩展插件并将其与其他Web应用程序组件集成。
核心方法
核心方法是影响/处理实例的方法:
// Start new fancybox instance
$.fancybox.open( items, opts, index );
// Get refrence to currently active fancybox instance
$.fancybox.getInstance();
// Close currently active fancybox instance (pass `true` to close all instances)
$.fancybox.close();
// Close all instances and unbind all events
$.fancybox.destroy();
启动fancybox
手动创建组对象时,每个项应遵循以下模式:
{
src : '' // Source of the content
type : '' // Content type: image|inline|ajax|iframe|html (optional)
opts : {} // Object containing item options (optional)
}
以编程方式打开图库的示例:
$.fancybox.open([
{
src : '1_b.jpg',
opts : {
caption : 'First caption',
thumb : '1_s.jpg'
}
},
{
src : '2_b.jpg',
opts : {
caption : 'Second caption',
thumb : '2_s.jpg'
}
}
], {
loop : false
});
也可以只传递一个对象。打开内联内容的示例:
$.fancybox.open({
src : '#hidden-content',
type : 'inline',
opts : {
afterShow : function( instance, current ) {
console.info( 'done!' );
}
}
});
如果您希望快速显示某些html内容(例如,消息),则可以使用更简单的语法。不要忘记在内容周围使用包装元素。
$.fancybox.open('<div class="message"><h2>Hello!</h2><p>You are awesome!</p></div>');
组项也可以是jQuery对象的集合。例如,这可用于显示内联元素组:
$('#test').on('click', function() {
$.fancybox.open( $('.inline-gallery'), {
touch: false
});
});
实例方法
要使用这些方法,您需要插件对象的实例。有3种常用方法可供参考。
1)使用API方法获取当前活动的实例:
var instance = $.fancybox.getInstance();
2)以编程方式启动fancybox:
var instance = $.fancybox.open(
// Your content and options
);
3)在回调中 - 第一个参数始终是对当前实例的引用:
$('[data-fancybox="gallery"]').fancybox({
afterShow : function( instance, current ) {
console.info( instance );
}
});
获得fancybox实例的引用后,可以使用以下方法:
// Go to next gallery item
instance.next( duration );
// Go to previous gallery item
instance.previous( duration );
// Switch to selected gallery item
instance.jumpTo( index, duration );
// Check if current image dimensions are smaller than actual
instance.isScaledDown();
// Scale image to the actual size of the image
instance.scaleToActual( x, y, duration );
// Check if image dimensions exceed parent element
instance.canPan();
// Scale image to fit inside parent element
instance.scaleToFit( duration );
// Update position and content of all slides
instance.update();
// Update slide position and scale content to fit
instance.updateSlide( slide );
// Update infobar values, navigation button states and reveal caption
instance.updateControls( force );
// Load custom content into the slide
instance.setContent( slide, content );
// Show loading icon inside the slide
instance.showLoading( slide );
// Remove loading icon from the slide
instance.hideLoading( slide );
// Try to find and focus on the first focusable element
instance.focus();
// Activates current instance, brings it to the front
instance.activate();
// Close instance
instance.close();
你也可以这样做:
$.fancybox.getInstance().jumpTo(1);
或者干脆:
$.fancybox.getInstance('jumpTo', 1);
活动
fancybox引发了几个事件:
beforeLoad : Before the content of a slide is being loaded
afterLoad : When the content of a slide is done loading
beforeShow : Before open animation starts
afterShow : When content is done loading and animating
beforeClose : Before the instance attempts to close. Return false to cancel the close.
afterClose : After instance has been closed
onInit : When instance has been initialized
onActivate : When instance is brought to front
onDeactivate : When other instance has been activated
事件回调可以设置为传递给fancybox初始化函数的options对象的函数属性:
<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实例和当前图库对象(如果存在)。
也可以为所有实例附加事件处理程序。为了防止干扰其他脚本,这些事件已被命名为.fb
。这些处理程序接收3个参数 - 事件,当前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;
}
}
模块
fancybox代码分为几个扩展核心功能的文件(模块)。如果需要,您可以通过排除不必要的模块来构建自己的fancybox版本。每个人都有自己的js
和/或css
文件。
某些模块可以通过编程方式进行定制和控制。所有可能选项列表:
fullScreen: {
autoStart: false
},
touch : {
vertical : true, // Allow to drag content vertically
momentum : true // Continuous movement when panning
},
// Hash value when initializing manually,
// set `false` to disable hash change
hash : null,
// Customize or add new media types
// Example:
/*
media : {
youtube : {
params : {
autoplay : 0
}
}
}
*/
media : {},
slideShow : {
autoStart : false,
speed : 4000
},
thumbs : {
autoStart : false, // Display thumbnails on opening
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
},
share: {
url: function(instance, item) {
return (
(!instance.currentHash && !(item.type === "inline" || item.type === "html") ? item.origSrc || item.src : false) || window.location
);
},
tpl:
'<div class="fancybox-share">' +
"<h1>{{SHARE}}</h1>" +
"<p>" +
'<a class="fancybox-share__button fancybox-share__button--fb" href="https://www.facebook.com/sharer/sharer.php?u={{url}}">' +
'<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="m287 456v-299c0-21 6-35 35-35h38v-63c-7-1-29-3-55-3-54 0-91 33-91 94v306m143-254h-205v72h196" /></svg>' +
"<span>Facebook</span>" +
"</a>" +
'<a class="fancybox-share__button fancybox-share__button--tw" href="https://twitter.com/intent/tweet?url={{url}}&text={{descr}}">' +
'<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="m456 133c-14 7-31 11-47 13 17-10 30-27 37-46-15 10-34 16-52 20-61-62-157-7-141 75-68-3-129-35-169-85-22 37-11 86 26 109-13 0-26-4-37-9 0 39 28 72 65 80-12 3-25 4-37 2 10 33 41 57 77 57-42 30-77 38-122 34 170 111 378-32 359-208 16-11 30-25 41-42z" /></svg>' +
"<span>Twitter</span>" +
"</a>" +
'<a class="fancybox-share__button fancybox-share__button--pt" href="https://www.pinterest.com/pin/create/button/?url={{url}}&description={{descr}}&media={{media}}">' +
'<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="m265 56c-109 0-164 78-164 144 0 39 15 74 47 87 5 2 10 0 12-5l4-19c2-6 1-8-3-13-9-11-15-25-15-45 0-58 43-110 113-110 62 0 96 38 96 88 0 67-30 122-73 122-24 0-42-19-36-44 6-29 20-60 20-81 0-19-10-35-31-35-25 0-44 26-44 60 0 21 7 36 7 36l-30 125c-8 37-1 83 0 87 0 3 4 4 5 2 2-3 32-39 42-75l16-64c8 16 31 29 56 29 74 0 124-67 124-157 0-69-58-132-146-132z" fill="#fff"/></svg>' +
"<span>Pinterest</span>" +
"</a>" +
"</p>" +
'<p><input class="fancybox-share__input" type="text" value="{{url_raw}}" /></p>' +
"</div>"
}
几个例子
在开始时显示缩略图:
$('[data-fancybox="images"]').fancybox({
thumbs : {
autoStart : true
}
});
如果显示隐藏的视频元素,请自定义共享网址:
$('[data-fancybox="test-share-url"]').fancybox({
buttons : ['share', 'close'],
hash : false,
share : {
url : function( instance, item ) {
if (item.type === 'inline' && item.contentType === 'video') {
return item.$content.find('source:first').attr('src');
}
return item.src;
}
}
});
如果你要检查fancybox实例对象,你会发现相同的密钥是captialized - 这些是每个模块对象的引用。此外,您会注意到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();
如果要禁用哈希模块,请使用此代码段(包含JS文件后):
$.fancybox.defaults.hash = false;
常问问题
#1打开/关闭会导致固定元素跳转
只需将compensate-for-scrollbar
CSS类添加到固定定位元素即可。使用Bootstrap导航栏组件的示例:
<nav class="navbar navbar-inverse navbar-fixed-top compensate-for-scrollbar">
<div class="container">
..
</div>
</nav>
该脚本测量滚动条的宽度并创建
compensate-for-scrollbar
使用此margin-right
属性值的CSS类
。因此,如果你的元素有
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') || '';
if ( item.type === 'image' ) {
caption = (caption.length ? caption + '<br />' : '') + '<a href="' + item.src + '">Download image</a>' ;
}
return caption;
}
});
在标题中添加当前图像索引和图像计数(图库中的图像总数):
$( '[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>';
}
});
Inside
caption
方法,
this
指的是被点击的元素。使用不同来源标题的示例:
$( '[data-fancybox]' ).fancybox({
caption : function( instance, item ) {
return $(this).find('figcaption').html();
}
});
#3如何在工具栏中创建自定义按钮
创建可重用按钮的示例:
// Create template for the button
$.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>';
// Make button clickable using event delegation
$('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');
});
// Customize buttons
$( '[data-fancybox="images"]' ).fancybox({
buttons : [
'fb',
'close'
]
});
#4如何重新定位缩略图网格
目前没有JS选项可以更改缩略图网格位置。但是fancybox的设计使您可以使用CSS来更改每个块的位置或尺寸(例如,内容区域,标题或缩略图网格)。如果需要,这使您可以自由地完全更改模态窗口的外观。 在CodePen上查看演示
#5如何禁用触摸手势/滑动
如果要使内容可选择或可点击,您有两种选择:
-
通过设置完全禁用触摸手势
touch:false
-
将
data-selectable="true"
属性添加 到您的html元素
#6 Slider / carousel添加克隆的重复项目
如果要将fancybox与slider / carousel脚本组合在一起,并且该脚本克隆项目以启用无限导航,则复制的项目将显示在库中。为了避免这种情况 - 1)在除克隆之外的所有项目上初始化fancybox; 2)在克隆的项目上添加自定义点击事件,并在相应的“真实”项目上触发点击事件。以下是使用Slick滑块的示例:
// Init fancybox
// =============
var selector = '.slick-slide:not(.slick-cloned)';
// Skip cloned elements
$().fancybox({
selector : selector,
backFocus : false
});
// Attach custom click event on cloned elements,
// trigger click event on corresponding link
$(document).on('click', '.slick-cloned', function(e) {
$(selector)
.eq( ( $(e.currentTarget).attr("data-slick-index") || 0) % $(selector).length )
.trigger("click.fb-start", {
$trigger: $(this)
});
return false;
});
// Init Slick
// ==========
$(".main-slider").slick({
slidesToShow : 3,
infinite : true,
dots : false,
arrows : false
});