单击更改颜色文本

时间:2012-08-28 17:38:47

标签: jquery text onclick

当我点击并且div崩溃时,我希望文本可折叠组项目#1 变成红色,这是最好的方法吗?

这是我的案例

http://jsfiddle.net/STqCF/66/

2 个答案:

答案 0 :(得分:2)

您可以将.css方法与回调一起使用来切换颜色

$('.accordion').collapse();

$('.accordion').on('show hide', function(e){
    var $sib = $(e.target).siblings('.accordion-heading');
    $sib.css('color','red').find('.accordion-toggle i').toggleClass('icon-arrow-down icon-arrow-up', 200);
    $sib.find('a.accordion-toggle').css('color',function(){
        return $(e.target).hasClass('in') ? 'red':'#08C';
    });
});

http://jsfiddle.net/STqCF/82/

修改

要添加font-weight粗体,只需执行相同操作并链接另一个.css方法

$('.accordion').on('show hide', function(e){
    var $sib = $(e.target).siblings('.accordion-heading');
    $sib.css('color','red').find('.accordion-toggle i').toggleClass('icon-arrow-down icon-arrow-up', 200);
    $sib.find('a.accordion-toggle').css('color',function(){
        return $(e.target).hasClass('in') ? 'red':'#08C';
    }).css('font-weight',function(){
        return $(e.target).hasClass('in') ? 'bold':'';
    });
});

虽然更好的方法是使用css类来完成它并切换该类

$('.accordion').on('show hide', function(e) {
    var $sib = $(e.target).siblings('.accordion-heading');
    $sib.css('color', 'red').find('.accordion-toggle i').toggleClass('icon-arrow-down icon-arrow-up', 200);
    $sib.find('a.accordion-toggle').toggleClass('aCollapsed', $(e.target).hasClass('in'));
});​

http://jsfiddle.net/STqCF/112/

答案 1 :(得分:0)

这是另一种更适合我的风格的解决方案。

我不得不试着解释一下你的问题 - 如果我误解了你想要做的事情,请原谅我。

这会为未展开的标题添加is-off类,并为展开的一个标题添加is-on类。

http://jsfiddle.net/STqCF/111/

// Cache our jQuery objects so we don't have to fetch them repeatedly
var $accordion = $('.accordion'),
    $accordionHeadings = $accordion.find('.accordion-heading');

// Collapse the accordion initially
$accordion.collapse();

$accordion.on('show hide', function(e){
    $(e.target).siblings('.accordion-heading').find('.accordion-toggle i').toggleClass('icon-arrow-down icon-arrow-up', 200);
});

// Bind an event to give an is-on state to the current headline and an is-off state to all other headlines
$('.accordion').on('show', function (e) {
    var $target = $(e.target);

    // Reset the class states - remove all is-ons and add is-offs
    $accordionHeadings.removeClass('is-on')
    $accordionHeadings.addClass('is-off');

    // For only the current item, add the is-on class and remove is-off
    $target.siblings('.accordion-heading')
        .addClass('is-on')
        .removeClass('is-off');
});