Jquery - hide()然后fadeIn()然后fadeOut()有更清洁的方式吗?

时间:2010-09-15 08:35:58

标签: jquery

我正在尝试使用jQuery实现一些动画。我有它的工作,但我100%肯定有更清洁的更好的做法,我希望有人可以指出我正确的方向。

这是我的代码:

$(document).ready(function () {   
    $("#1-popup").hide(); // Hides the first popup
    $("#2-popup").hide(); // Hides the second popup
    $("#1-trigger").toggle(function () {
        $("#2-popup").fadeOut("slow"); // Hides the second popup just incase its showing
        $("#1-popup").fadeIn("slow"); // Fades in the first popup
    }, function () {
        $("#1-popup").fadeOut("slow"); // Fades out in the first popup
    });


    $("#2-trigger").toggle(function () {
        $("#1-popup").fadeOut("slow"); // Hides the first popup just incase its showing
        $("#2-popup").fadeIn("slow"); // Fades in the second popup
    }, function () {
        $("#2-popup").fadeOut("slow"); // Fades out the second popup
    });
});

无论如何在这里使用if语句有点麻烦吗?

3 个答案:

答案 0 :(得分:3)

如何更通用而不是为每个弹出窗口编写代码? : - )

<div class="popup" id="popup1">Hi I'm Popup 1</div>
<div class="popup" id="popup2">Hi I'm Popup 2</div>
<a class="trigger" rel="popup1">show popup 1</a>
<a class="trigger" rel="popup2">show popup 2</a>
<script>
var popups = $('.popup').hide();
$('a.trigger').click(function() {
  var popup = $('#'+$(this).attr('rel'));
  popups.not(popup.fadeIn()).fadeOut();
});
</script>

答案 1 :(得分:2)

您可以将切换代码移动到单独的函数中,并将其重用于不同的触发器。这更像是一般的重构,而不是jQuery特定的改进:

bindToggleTriggerAndFadePopups($("#1-trigger"), $("#1-popup"), $("#2-popup"))       
bindToggleTriggerAndFadePopups($("#2-trigger"), $("#2-popup"), $("#1-popup"))       

function bindToggleTriggerAndFadePopups($trigger, $popupToFadeIn, $popupToHide){
    $trigger.toggle(
        function(){
            $popupToHide.fadeOut("slow"); // Hides the first popup just incase its showing
            $popupToFadeIn.fadeIn("slow"); // Fades in the second popup
        },
        function(){
            $popupToFadeIn.fadeOut("slow"); // Fades out the second popup
        });
}

答案 2 :(得分:2)

$(document).ready(function () {

    $('#1-popup,#2-popup').hide(); // Hides the first and second popup

    $('#1-trigger,#2-trigger').toggle(function () {
        var num = parseInt(this.id);

        $('#1-popup,#2-popup').not('#'+num+'-popup').fadeOut('slow'); 
        $('#'+num+'-popup').fadeIn('slow'); 
    }, function () {

        $('#'+num+'-popup').fadeOut('slow'); 
    });

});

警告idrefer here的属性值无效。有了这个,你会在某些浏览器上遇到严重的问题。