Colorbox关闭、重新打开并保留事件

Colorbox close, reopen and keep events

本文关键字:保留 事件 新打开 关闭 Colorbox      更新时间:2023-09-26

我有一个小功能,它在一个颜色框中打开。我希望能够关闭彩盒并重新打开它。但是再次打开彩盒,事件就不再起作用了。

最小示例:

(function() {
    var $content = jQuery('<button>Test</button>');
    $content.on('click', function(){jQuery.colorbox.close()});
    jQuery.colorbox({
        width: '90%',
        height: '90%',
        html: $content
    });
    var $reopen = jQuery('<button>Reopen</button>');
    jQuery(document.body).append($reopen);
    $reopen.on("click", function() {
        jQuery.colorbox({
            width: '90%',
            height: '90%',
            html: $content
        });
    });
})()

使用上面的代码,我打开一个颜色框,然后可以使用$content按钮关闭该框(或执行其他操作)。如果我关闭盒子并用$reopen按钮重新打开它,$content上的点击事件将不再工作。

知道如何解决这个问题吗?要测试示例代码,可以使用http://www.jacklmoore.com/colorbox/example1/以包含所需的libsjquery和colorbox。

如果关闭colorbox,问题是删除内容。解决方法是使用inline选项来获得所需效果:

(function() {
    var $content = jQuery('<button>Test</button>');
    $content.on('click', function(){jQuery.colorbox.close()});
    jQuery.colorbox({
        width: '90%',
        height: '90%',
        inline: true,
        href: $content
    });
    $reopen = jQuery('<button>Reopen</button>');
    jQuery(document.body).append($reopen);
    $reopen.on("click", function() {
        jQuery.colorbox({
            width: '90%',
            height: '90%',
            inline: true,
            href: $content
        });
    });
})()

使用inline选项并将节点从html移动到href可以保存事件处理程序,并允许您以后重用该节点。Colorbox用伪<div>替换$content,并在调用close()时切换回来。