简体   繁体   English

淡入和淡出内容时,从上一个单击的元素中删除活动类

[英]Removing the active class from the previous clicked element when fading in and fading out content

I've created 3 buttons with a paragraph of content after each, when a button is clicked this will fade in the paragraph that follows it as well as adding an active class to that clicked button. 我已经创建了3个按钮,每个按钮后面都有一个段落内容,当单击一个按钮时,它会在其后的段落中消失,并为该单击的按钮添加一个活动类。 At the moment I have managed to achieve the fade in and fade out but i dont seem to be able to remove the active class from the previous clicked button, can anyone advise where I might be going wrong with this? 目前,我已经成功实现了淡入和淡出,但是我似乎无法从上一个单击的按钮中删除活动的课程,有人可以告诉我这可能在哪里出问题吗? also there is probably an easier/better way to create the effect Im working towards so all advice/help/suggestions are really welcome. 也可能有一种更容易/更好的方式来创造效果,我正努力争取所有的建议/帮助/建议。

Fiddle: http://jsfiddle.net/kyllle/nZFUP/3/ 小提琴: http : //jsfiddle.net/kyllle/nZFUP/3/

Thanks Kyle 谢谢凯尔

Try removing the .active class from all of the .clickMe links, then add the .active class to the currently clicked link: 尝试从所有.clickMe链接中删除.active类,然后将.active类添加到当前单击的链接中:

$(document).ready(function() {
    $('.clickMeInfo').hide();


    $('.clickMe').click(function() {
        $('.clickMeInfo').fadeOut('fast');
        $(this).next('.clickMeInfo').fadeIn('fasst');
        $('.clickMe').removeClass('active');
        $(this).addClass('active');
    });
});

You could also do some optimization since the same selectors will be used over and over: 您还可以进行一些优化,因为将反复使用相同的选择器:

$(document).ready(function() {
    //cache the elements instead of selecting them multiple times
    var $clickMe     = $('.clickMe'),
        $clickMeInfo = $('.clickMeInfo');
    $clickMeInfo.hide();

    $clickMe.click(function() {
        //find the index of the clicked element
        var $this = $(this),
            this_index = $clickMe.index($this);
        //fade-out all the info elements, then select only the clicked index and fade it in
        $clickMeInfo.fadeOut('fast').filter(':eq(' + this_index + ')').fadeIn('fast');

        $clickMe.removeClass('active');
        $this.addClass('active');
    });
});

Here is an update to your jsfiddle of the above optimization: http://jsfiddle.net/nZFUP/4/ 这是对上述优化的jsfiddle的更新: http : //jsfiddle.net/nZFUP/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM