2012-01-11 100 views
1

我写了一些JavaScript来显示和巧妙地隐藏工作人员页面上的信息。基本上,有3个标志和3组描述。如果您将鼠标悬停在设计标志上,则会显示设计团队的描述和图像,反之亦然。这里是我的代码来做到这一点:有没有更好的方法来写我的jQuery代码?

$('.emblem img:first').hover(
      function() { 
       $('.description:eq(1), .description:eq(2)').css({opacity : 0.2}); 
       $('.devStaff').css({opacity : 0.2}); 
      }, 
      function(){ 
       $('.description:eq(1), .description:eq(2)').css({opacity : 1}); 
       $('.devStaff').css({opacity : 1}); 
      } 
     ); 

     $('.emblem img:eq(1)').hover(
      function() { 
       $('.description:eq(0), .description:eq(2)').css({opacity : 0.2}); 
       $('.designStaff').css({opacity : 0.2}); 
      }, 
      function(){ 
       $('.description:eq(0), .description:eq(2)').css({opacity : 1}); 
       $('.designStaff').css({opacity : 1}); 
      } 
     ); 

     $('.emblem img:eq(2)').hover(
      function() { 
       $('.description:eq(0), .description:eq(1)').css({opacity : 0.2}); 
       $('.designStaff').css({opacity : 0.2}); 
      }, 
      function(){ 
       $('.description:eq(0), .description:eq(1)').css({opacity : 1}); 
       $('.designStaff').css({opacity : 1}); 
      } 
     ); 

现在看看这个,我觉得肯定是有更好的方式来做到这一点,我想知道是否有人将能够提供一些建议吗?

+2

根据您的描述,似乎这可能都是用CSS完成的。不是说使用JavaScript来做它是错误的,它只是少得多的代码。如果你在jsfiddle.net中构建它,你可能会得到一些非常好的答案。 – BZink 2012-01-11 17:16:02

+0

寻找重复的代码和保持不变的代码 - 提取变化的内容,模板保持不变,然后将变量注入模板。 – 2012-01-11 17:19:45

回答

1

一般情况下,你不应该重复自己(http://en.wikipedia.org/wiki/Don” t_repeat_yourself),

尝试调用一个更一般的功能,如:

function fadeOut(eqNum1, eqNum2) { 
    $('.description:eq('+eqNum1+'), .description:eq('+eqNum2+')').css({opacity : 0.2}); 
    $('.devStaff').css({opacity : 0.2}); 
} 
function fadeIn(eqNum1, eqNum2){ 
    $('.description:eq('+eqNum1+'), .description:eq('+eqNum2+')').css({opacity : 1}); 
    $('.devStaff').css({opacity : 1}); 
} 

$('.emblem img:first').hover(fadeOut(1,2), fadeIn(1,2)); 

$('.emblem img:eq(1)').hover(fadeOut(0,2),fadeIn(0,2)); 

$('.emblem img:eq(2)').hover(fadeOut(0,1),fadeIn(0,1)); 
1

您可以通过:lt(3)代替:first:eq(1):eq(2)

$('.emblem img:lt(3)').hover(
     function() { 
      $('.description:lt(2)').css({opacity : 0.2}); 
      $('.designStaff').css({opacity : 0.2}); 
     }, 
     function(){ 
      $('.description:lt(2)').css({opacity : 1}); 
      $('.designStaff').css({opacity : 1}); 
     } 
    ); 
相关问题