0

我在搞乱一个单页网站。我希望 div 在导航中的点击事件上淡入淡出。.currentPage 将在加载时显示,并在单击其他导航时淡出。我把它放在jsFiddle上。

问题:

  1. 没有发生淡出

  2. fadeIn 仅在您单击 nav a 几次后才会发生。

  3. 理想情况下,我希望这样,如果您单击任何 nav a 是 .current,什么都不会发生 - 现在,如果您单击,它会再次运行脚本。

愿望清单:

  1. 是否有更简洁的 jQuery 方法通过导航淡入和淡出 div?我只是有点摸索,没有太多线索......

HTML

<nav>
    <a href="#" id="workPage" class="current">Work</a>
    <a href="#" id="aboutPage">About</a>
    <a href="#" id="designPage">Design</a>
</nav>

<div class="box work currentPage">WORK</div>
<div class="box about">ABOUT</div>
<div class="box design">DESIGN</div>

jQuery

$('nav a').click(function () {
    if (!$(this).hasClass("current")) {
        $('.current').removeClass("current");
        $(this).addClass("current");
    }

}); //using this to set a "current" state in the nav


$("#workPage").click(function () {
    $('.currentPage').fadeOut(500, function (){
        $('.work').addClass('currentPage').fadeIn(500);
        }).removeClass('currentPage');
    });


$("#aboutPage").click(function () {
    $('.currentPage').fadeOut(500, function (){
        $('.about').addClass('currentPage').fadeIn(500);
    }).removeClass('currentPage');
});

$("#designPage").click(function () {
    $('.currentPage').fadeOut(500, function (){
        $('.design').addClass('currentPage').fadeIn(500);
    }).removeClass('currentPage');
});
4

1 回答 1

1

您应该在完整回调中删除当前类

$('nav a').click(function (e) {
    if (!$(this).hasClass("current")) {
        $('.current').removeClass("current");
        $(this).addClass("current");
    } else {
        e.stopImmediatePropagation();
    }

});


$("#workPage").click(function () {
    $('.currentPage').fadeOut(500, function (){
        $(this).removeClass('currentPage')
        $('.work').addClass('currentPage').fadeIn(1000);
    });
});


$("#aboutPage").click(function () {
    $('.currentPage').fadeOut(500, function (){
        $(this).removeClass('currentPage')
        $('.about').addClass('currentPage').fadeIn(1000);
    })
});

$("#designPage").click(function () {
    $('.currentPage').fadeOut(500, function (){
        $(this).removeClass('currentPage')
        $('.design').addClass('currentPage').fadeIn(1000);
    })
});

演示:小提琴

于 2013-09-17T06:26:43.183 回答