Fancybox - 根据 div id 添加 class 到标题

Fancybox - add class to the title depending on div id

我有 css class 定义背景颜色的文件,例如 .blue、.red 等。我想添加特定的 class 到包含 class 'fancybox-title' 的 div,具体取决于属于 fancybox

的 id
<div class="fancybox-skin">
    <div class="fancybox-title fancybox-title-inside-wrap">Welcome</div>  //here I want to add class, for example '.blue'...
    <div class="fancybox-outer">
        <div class="fancybox-inner">
            <div style="display: block;" id="login-register-fancybox"></div>  //depending on the ID from this line of code
        </div>
    </div>
</div>

我在里面有过几次尝试:

$('.fancybox').fancybox({
    'beforeLoad': function(){

    }
});

包括尝试通过 ID、开关等查找元素,但脚本开始看起来又大又乱,却没有给我想要的结果。我相信有更简单的方法可以做到这一点,只是无法弄清楚。有人可以帮忙吗?

您可以使用 event 上的 $(this).fancybox('instance') 来定位 fancybox 的实例。它会给你一个具有许多属性的对象。其中之一是元素,您可以在其上调用 parentNode 或任何您需要的东西。这样会给你调用 fancybox:

a 元素的父元素的 id
$('.fancybox').fancybox({
    'beforeLoad': function(){
          $(this).fancybox('instance')[0].element[0].parentNode.id

    }
});

我将为您提供两种解决方案:

首先:您的问题 "depending on the id that belongs to the fancybox" 的答案使用了 switch 语句并且 类 是硬编码的。 this 包含一个属性content:加载的内容。通过将内容包装在 jQuery object 中,我们可以获得内容的 id。

其次:为了让你的代码更通用我给你的HTML添加了一个新属性data-title-class,这个属性的这个值被设置添加到fancybox标题的类 .

两种解决方案都使用回调 afterShow,因为在较早的回调中 fancybox-title 尚未添加。

$('.fancybox').fancybox({ afterShow: function()
{
    // First solution, based on id of content.
    var titleClass;
    switch($(this.content).attr('id'))
    {
        case 'register':
            titleClass = 'blue';
            break;
        case 'login':
            titleClass = 'red';
            break;
    }
    $('.fancybox-title span').addClass(titleClass);
    
    //Second solution, based on data attribute.    
    if($(this.content).attr('data-title-class'))
    {
        $('.fancybox-title span').addClass($(this.content).attr('data-title-class'));
    }
} });
#register, #login { display: none; }
.blue { background-color: #00f !important; }
.red { background-color: #f00 !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.pack.js"></script>

<div id="register">
    registering...
</div>
<div id="login" data-title-class="red"><!-- Second solution -->
    logging in...
</div>

<a href="#register" title="register now!" class="fancybox">register</a><br />
<a href="#login" title="login now!" class="fancybox">login</a>