如何在JQuery Accordion上添加活动类

时间:2014-05-30 09:38:49

标签: javascript jquery html css accordion

我正在谷歌搜索一个垂直的Jquery手风琴菜单,并且我在我的网站上找到了我需要的代码。我在Javascript方面经验不足。所以,从我的Javascript代码我需要添加一个" Active"活动选项卡的类。任何人都可以帮助我。

HTML

<div class="accordian">
    <ul>
        <li class="even" style="padding-left: 30px; cursor: pointer;">Quisque at erat vitae</li>
        <li class="dimension" style="display: block;">Test1</li>
        <li class="odd" style="cursor: pointer; padding-left: 10px;">Sed euismod massa</li>
        <li class="dimension" style="display: none;">Test2</li>
        <li class="even" style="cursor: pointer; padding-left: 10px;">Proin et orci sit amet</li>
        <li class="dimension" style="display: none;">Test3</li>
    </ul>
</div>

的CSS

<style type="text/css">
.accordian {
    width: 400px;
    margin: 50px auto;
}

.accordian li {
    list-style-type: none;
    padding: 0 5px;
}

.dimension {
    height: 400px;
}

.even, .odd {
    font-weight: bold;
    height: 27px;
    padding-top: 3px;
    padding-left: 10px;
}

.even {
    border: 1px solid #d8d8d8;
    background-color: #ececec;
}

.odd {
    border: 1px solid black;
    background: #333;
    color: white;
}
</style>

的Javascript

$(function() {
    // Hide all the content except the first
    $('.accordian li:odd:gt(0)').hide();

    // Add a padding to the first link
    $('.accordian li:first').animate( {
        paddingLeft:"30px"
    } );

    // Add the dimension class to all the content
    $('.accordian li:odd').addClass('dimension');

    // Set the even links with an 'even' class
    $('.accordian li:even:even').addClass('even');

    // Set the odd links with a 'odd' class
    $('.accordian li:even:odd').addClass('odd');

    // Show the correct cursor for the links
    $('.accordian li:even').css('cursor', 'pointer');

    // Handle the click event
    $('.accordian li:even').click( function() {
        // Get the content that needs to be shown
        var cur = $(this).next();

        // Get the content that needs to be hidden
        var old = $('.accordian li:odd:visible');

        // Make sure the content that needs to be shown 
        // isn't already visible
        if ( cur.is(':visible') )
            return false;

        // Hide the old content
        old.slideToggle(500);

        // Show the new content
        cur.stop().slideToggle(500);

        // Animate (add) the padding in the new link
        $(this).stop().animate( {
            paddingLeft:"30px"
        } );

        // Animate (remove) the padding in the old link
        old.prev().stop().animate( {
            paddingLeft:"10px"
        } );
    } );
});

1 个答案:

答案 0 :(得分:0)

您想要将类添加到哪个元素(已单击的选项卡或该选项卡显示的内容)并不完全清楚。

如果您想要标签本身,请使用:$(this).addClass("current");,但如果您需要内容,请使用:$(this).next().addClass("current");

您也几乎肯定想要使用old.removeClass("current");

删除它

Demo