2012-02-14 83 views
0

我寫了一個小的jquery代碼,但它看起來非常多餘和幼稚。任何人都可以幫助縮短它或使效率更高?jquery代碼縮短

下面的代碼:

// DIM The Light Effect 
    var dimlight = $(".dimlight"), 
    showlight = $(".showlight"), 
    overlay = $("#overlay") 
    playerlive = $("#player_live"), 
    lightswitch = $(".light_switch") 

     playerlive.mouseover(function(){ 

     lightswitch.show(); 
     }); 

     playerlive.mouseout(function(){ 

     lightswitch.hide(); 
     }); 

     dimlight.click(function(){ 

     overlay.fadeIn(); 
     dimlight.hide(); 
     showlight.show(); 
     }); 

     showlight.click(function(){ 
     overlay.fadeOut(); 
     dimlight.show(); 
     showlight.hide(); 
     }); 

     showlight.click(function(){ 
     overlay.fadeOut(); 
     dimlight.show(); 
     showlight.hide(); 
     }); 

THX很多已

+0

你有'showlight.click(...)'兩次... – 2012-02-14 11:15:28

回答

0

爲什麼你不只是做:

$('.dimlight, .showlight').click(function(){ 
    if ($(this).hasClass('dimlight')) { 
     overlay.fadeIn(); 
     dimlight.hide(); 
     showlight.show(); 
    } else { 
     overlay.fadeOut(); 
     dimlight.show(); 
     showlight.hide(); 
    } 
    }); 
+0

有一次是'dimlight.show();',另一次'dimlight.hide();' – 2012-02-14 11:16:01

+0

@FelixKling已經改變它 – PeeHaa 2012-02-14 11:17:24

+0

完美地工作。 Thx一堆。 – user546585 2012-02-14 11:22:12

1

你可以重寫如下整個代碼:

$("#player_live").hover(function(){ 
    $(".light_switch").toggle(); 
}); 

var elems = $('.dimlight, .showlight'); 
elems.click(function(){ 
    elems.toggle(); 
    $("#overlay").fadeToggle(); 
}); 
+0

爲什麼不''(「。light_switch」)。toggle()'? – 2012-02-14 11:31:16

+0

ofcourse可以做,但因爲這是在mouseover和mouseout,2不同的功能,使用show hide將避免混淆。 – 2012-02-14 11:33:20

+0

我的意思是'$(「#player_live」)。hover(function(){$(「。light_switch」)。toggle();});' - 參見[here](http://jsfiddle.net/TVULe/ ) – 2012-02-14 11:36:29