[英]Launch fancyBox from button click
我遇到了fancyBox v2的一個小問題。
我想在按鈕點擊時啟動fancyBox。 點擊后,它將加載列表中的所有圖像(來自的src屬性)。
我創建了這個jsfiddle來展示我想要做的事情: http : //jsfiddle.net/fPFZg/
jQuery(document).ready(function($) {
$('button').on('click', function() {
$.fancybox();
});
});
任何人都可以看到這是可能的嗎?
我有同樣的問題,發現以下是一個更簡單的方法:
<button class="fancybox" value="Open Fancybox">Open Fancybox</button>
<div class="hidden" id="fancybox-popup-form">
(your Fancybox content goes in here)
</div>
$('.fancybox').click(function () {
$.fancybox([
{ href : '#fancybox-popup-form' }
]);
});
.hidden { display: none; }
Fancybox文檔 (單擊“API方法”選項卡,然后閱讀第一個方法,稱為“打開”)。
你可以像這樣使用它:
$.fancybox.open([
{
href : 'http://fancyapps.com/fancybox/demo/1_b.jpg',
title : '1st title'
},
{
href : 'http://fancyapps.com/fancybox/demo/2_b.jpg',
title : '2nd title'
}
], {
padding : 0
});
你的代碼不起作用,因為這個$.fancybox();
沒有告訴fancybox打開什么,所以什么都不做。
如果您不想編輯html中的每個鏈接,我會怎么做:
1)。 在<ul>
標簽中添加一個ID
,以便我們可以使用該選擇器
<ul id="images">
2)。 將fancybox綁定到所有<a>
錨點,這些錨點是元素#images
子元素
var fancyGallery = $("#images").find("a"); // we cache the selector here
fancyGallery.attr("rel","gallery").fancybox({
type: "image"
});
請注意 ,我們正在向所有錨點添加一個rel
屬性,因此它們將成為同一個庫的一部分
3)。 將一個click
事件綁定到該button
(我建議你也給它一個ID
以便將來不會弄亂其他可能的按鈕 )觸發現有的fancybox腳本如上所述,所以使用這個html
<button id="fancyLaunch">Launch Fancybox</button>
使用這個腳本
$('#fancyLaunch').on('click', function() {
fancyGallery.eq(0).click(); // triggers a click
});
請注意我們使用方法.eq()
從第一個項目啟動庫(javascript中的第一個index
始終為0)
總結一下,您的整個腳本可能如下所示:
jQuery(document).ready(function($) {
var fancyGallery = $("#images").find("a");
fancyGallery.attr("rel","gallery").fancybox({
type: "image"
});
$('#fancyLaunch').on('click', function() {
fancyGallery.eq(0).click();
});
});
請參閱JSFIDDLE
你的HTML:
<ul>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
你的jQuery:
$(document).ready(function() {
$('button').on('click', function() {
$.fancybox($("a.fancybox"));
});});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.