jQuery разборный div, сворачивание 2-ой div

0

Я дизайнер, пытающийся найти исправление для моей jQuery разборной проблемы div. (Я новичок в jQuery, но у меня хорошая ручка для html и CSS). Кажется, я не могу найти то, что я ищу на форумах, поэтому я делаю это. Надеюсь, кто-то может мне помочь.

У меня есть панель со вкладкой заголовка и 2 divs. Я хочу, чтобы на вкладке панели был установлен триггер open/close (с графическим изображением), и только при закрытии второго div закрывается. У меня первый div всегда показывался, а второй div - это параметры, которые я хотел бы открыть/закрыть при выборе кнопки на вкладке панели.

Я использую разборный код div Ramin Hossaini в качестве отправной точки:

Здесь CSS:

h1 {
    margin-top:20px;
    margin-bottom:20px;
}

p {
    margin-bottom:10px;
}

.module {
    border:1px solid #ccc;
    width: 400px;
    margin-bottom:20px;
}

.module .header  {
    background-color:#efefef;
    padding-left:10px;
}

.module .header h1 {
    margin:0;
    display:inline;
    font-size:16px;
}

.module .content{
    clear:both;
    padding:10px;
}

.module .placeholder {
    margin-top:1px;
    margin-right:2px;
}

.module .expand {
    float:left;
    display:inline;
    background-image:url(../images/toggle-sprite.png);
    background-position: 0px -16px;
    width:16px;
    height:16px;
}   

.module .collapse {
    float:left;
    display:inline;
    background-image:url(../images/toggle-sprite.png);
    background-position: 0px 0px;
    width:16px;
    height:16px;
    padding-left: 20px;
    background-repeat: no-repeat;
}

Вот мой html:

<div class="panel module">

<div class="panelTab header">
    <h1>Header #1</h1>
</div>

<div class="content 1">
          <p>I want this content to always show.</p>
     </div>

<div class="content 2"> <!-- the 'content' class is only for styling -->
    <p>I want this panel to collapse and expand.</p>
</div>

</div>

И jquery, который я не совсем понимаю:

jQuery.collapsible = function(selector, identifier) {

//toggle the div after the header and set a unique-cookie
$(selector).click(function() {
    $(this).next().slideToggle('fast', function() {
        if ( $(this).is(":hidden") ) {
            $.cookie($(this).prev().attr("id"), 'hide');
                 $(this).prev().children(".placeholder").removeClass("collapse").addClass("expand");
        }
        else {
            $.cookie($(this).prev().attr("id"), 'show');
            $(this).prev().children(".placeholder").removeClass("expand").addClass("collapse");
        }
    });
    return false;
}).next();


//show that the header is clickable
$(selector).hover(function() {
    $(this).css("cursor", "pointer");
});

/*
 * On document.ready: should the module be shown or hidden?
 */
var idval = 0;  //increment used for generating unique ID's
$.each( $(selector) , function() {

    $($(this)).attr("id", "module_" + identifier + idval);  //give each a unique ID

    if ( !$($(this)).hasClass("collapsed") ) {
        $("#" + $(this).attr("id") ).append("<span class='placeholder collapse'></span>");
    }
    else if ( $($(this)).hasClass("collapsed") ) {
        //by default, this one should be collapsed
        $("#" + $(this).attr("id") ).append("<span class='placeholder expand'></span>");
    }

    //what has the developer specified? collapsed or expanded?
    if ( $($(this)).hasClass("collapsed") ) {
        $("#" + $(this).attr("id") ).next().hide();
        $("#" + $(this).attr("id") ).children("span").removeClass("collapse").addClass("expand");
    }
    else {
        $("#" + $(this).attr("id") ).children("span").removeClass("expand").addClass("collapse");
    }


    if ( $.cookie($(this).attr("id")) == 'hide' ) {
        $("#" + $(this).attr("id") ).next().hide();
        $("#" + $(this).attr("id") ).children("span").removeClass("collapse").addClass("expand");
    }
    else if ( $.cookie($(this).attr("id")) == 'show' ) {
        $("#" + $(this).attr("id") ).next().show();
        $("#" + $(this).attr("id") ).children(".placeholder").removeClass("expand").addClass("collapse");
    }


    idval++;
});

};
  • 0
    Данный jquery влияет только на первый div после заголовка. Используя этот плагин jquery, вы не получите то, что хотите, вам нужно написать свой собственный или найти другой, который будет нацелен на div, который вы хотите переключить.

2 ответа

1
Лучший ответ

Я использовал следующий jquery:

$('#toggle').on('click', function(){
    if($('#toggle').text()==='Open'){
        $('#collapsible').slideUp();
        $('#toggle').text('Close');
    }else{
        $('#collapsible').slideDown();
        $('#toggle').text('Open');
    }
});

вы можете увидеть, как он ворует в этой скрипке: http://jsfiddle.net/yhTpW/

  • 0
    @Idmo: Как это можно изменить, чтобы использовать изображение для открытия и закрытия? Мне не нужна копия, я просто хочу использовать изображения (1 для открытого, 1 для закрытого)? Любая помощь будет принята с благодарностью.
1

Я бы не использовал этот код jQuery вообще, а более простой:

jQuery( function(){
    jQuery(".panel .panelTab").css("cursor","pointer").click( function(){
        if( jQuery(".panel .2").toggle().is(":visible")){
            jQuery(this).removeClass("collapse").addClass("expand");
        } else {
            jQuery(this).removeClass("expand").addClass("collapse");
        }
    });
});

Ещё вопросы

Сообщество Overcoder
Наверх
Меню