如何使用 colorbox 在页面上显示隐藏的 div 而无需进行硬编码?

2024-03-08

我正在使用 Colorbox 在我的页面上显示隐藏 div 的 html 内容。我可以让它与以下内容完美配合:

$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});

这将显示 ID 为 344 的 div。

但是,因为我正在尝试使用 WordPress 构建可扩展的动态页面,所以我希望能够通过函数获取 div 的 ID,而不是在 jquery 调用中对它们进行硬编码。

我修改了杰克摩尔的例子:

$("a[rel='example']").colorbox({title: function(){
    var url = $(this).attr('href');
    return '<a href="'+url+'" target="_blank">Open In New Window</a>';
}}); 

这样它看起来像这样:

$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
    var elementID = $(this).attr('id');
    return elementID;
}}); 

问题在于 colorbox 函数的 href 属性正在查找 ID 前面带有 # 标记的字符串。我尝试了各种将 # 连接到函数前面的方法,包括返回值中的 #,以及将 # 连接到 elementID 变量。没有运气。

我还尝试使用 Jack 示例中的语法(没有运气),以便我的 return 语句如下所示:

return "#'+elementID+'";

我认为我的基本问题是:如何使用 colorbox 在页面上显示隐藏的 div,而不对所有内容进行硬编码?

感谢您的帮助, 吉尔特


我真的不喜欢上面给出的任何答案。我就是这样做的(类似但不完全相同)。 我还为那些刚接触 Javascript 和 colorbox 插件的人充分评论了它。

$(document).ready(function() { //waits until the DOM has finished loading
    if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
        $('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
            var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
            $(url).hide(); //hides the lightbox content div
            $(this).colorbox({
                 inline:true, // so it knows that it's looking for an internal href
                 href:url, // tells it which content to show
                 width:"70%",
                 onOpen:function(){ //triggers a callback when the lightbox opens
                    $(url).show(); //when the lightbox opens, show the content div
                 },
                 onCleanup:function(){
                    $(url).hide(); //hides the content div when the lightbox closes
                 }
            }).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
              //you could also use "return false" for the same effect but I proffered that way
        })
     }
});

这是 HTML:

<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
     <p>Lightbox content goes here</p>
</div>

我认为它可以在一页上使用多个灯箱,但我还没有对此进行测试。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 colorbox 在页面上显示隐藏的 div 而无需进行硬编码? 的相关文章

随机推荐