我想知道如何简化此代码

时间:2014-04-03 19:45:34

标签: jquery

我真的只想知道如何折叠此代码。它工作正常,但我厌倦了总是不得不复制和粘贴多行jquery。任何帮助将不胜感激。 http://jsfiddle.net/eE35W/5/

$(document).ready(function(){
  $(".creep1").mouseover(function(){
    $(".deep1").animate({
      left:'0px',
      opacity:'100',
      height:'100px',
      width:'300px'
    });
  });
  $(".creep1").mouseout(function(){
    $(".deep1").animate({
      left:'0px',
      opacity:'0.5',
      height:'100px',
      width:'10px'
    });
  });
  $(".creep2").mouseover(function(){
    $(".deep2").animate({
      left:'0px',
      opacity:'100',
      height:'100px',
      width:'300px'
    });
  });
  $(".creep2").mouseout(function(){
    $(".deep2").animate({
      left:'0px',
      opacity:'0.5',
      height:'100px',
      width:'10px'
    });
  });
  $(".creep3").mouseover(function(){
    $(".deep3").animate({
      left:'0px',
      opacity:'100',
      height:'100px',
      width:'300px'
    });
  });
  $(".creep3").mouseout(function(){
    $(".deep3").animate({
      left:'0px',
      opacity:'0.5',
      height:'100px',
      width:'10px'
    });
  });
  $(".creep").click(function(){
    $(".wrap1, .wrap2, .wrap3").toggle({
      left:'0px',
      opacity:'100',
      height:'100px',
      width:'300px'
    });
  });
});

2 个答案:

答案 0 :(得分:1)

而不是creep1,creep2 ...... creepn和deep1,deep2 ... deepn,只需指定常用类 creep deep 。并简化您的代码,

$(".creep").mouseout(function()
{
    $(this).next().animate({ // Since deep is next div to creep (as per your code)
      left:'0px',
      opacity:'0.5',
      height:'100px',
      width:'10px'
    });
});

同样,您可以编写mouseover函数。

答案 1 :(得分:0)

如果您更改为公共类而不是编号类,则可以执行此操作:

$(document).ready(function(){
   $(".creep" ).hover(function(){
     $(this).next().animate({
       opacity:'100',
       width:'300px'
       // since you are not changing the values 
       // of the other properties they have been left out
     });
   }),function(){
     $(this).next().animate({
       opacity:'0.5',
       width:'10px'
     });
   });
  };
 //remaining code
});