点击按钮启动fancyBox

Launch fancyBox from button click

本文关键字:fancyBox 启动 按钮      更新时间:2023-09-26

我在使用fancyBox v2时遇到了一个小问题。

我想在按钮点击上启动fancyBox。一旦点击,它将加载列表中的所有图像(从src属性)。

我已经创建了这个jsfiddle来显示我要做的事情:http://jsfiddle.net/fPFZg/

jQuery(document).ready(function($) {
    $('button').on('click', function() {
        $.fancybox(); 
    });
});

有人知道这是怎么可能的吗?

我有同样的问题,发现下面是一个更简单的方法:

HTML

    <button class="fancybox" value="Open Fancybox">Open Fancybox</button>
    <div class="hidden" id="fancybox-popup-form">
        (your Fancybox content goes in here)
    </div>
jQuery

    $('.fancybox').click(function () {
        $.fancybox([
            { href : '#fancybox-popup-form' }
        ]);
    });
CSS

    .hidden { display: none; }

进一步阅读

Fancybox Docs(单击"API方法"选项卡,然后阅读第一个方法,称为"Open")

你可以这样使用:

    $.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)。将ID添加到<ul>标签中这样我们就可以使用

这样的选择器
<ul id="images">

2)。将fancybox绑定到元素#images的子元素<a>锚,如

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(); 
    });
});
<<p>看到strong> 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")); 
});});