2010-12-21 4 views
2

기본적으로이 코드 중 일부를 다듬 으려하지만이 방법을 잘 모릅니다. 9 개의 DIV가 다른 지점에 절대적으로 배치되었습니다. 그들은 모두 회색이지만 끌려 가면 DIV가 사라지고 페이드 아웃되고 해당 DIV가 페이드 인합니다.이 방법을 쓸 수있는 더 좋은 방법이 있습니까?이 jQuery 함수를 작성하는 더 나은 방법은?

$('#l1').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l1c').fadeIn('300') 
}); 
$('#l2').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l2c').fadeIn('300') 
}); 
$('#l3').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l3c').fadeIn('300') 
}); 
$('#l4').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l4c').fadeIn('300') 
}); 
$('#l5').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l5c').fadeIn('300') 
}); 
$('#l6').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l6c').fadeIn('300') 
}); 
$('#l7').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l7c').fadeIn('300') 
}); 
$('#l7').hover(function() { 
    $(this).fadeOut('300'); 
    $('#l7c').fadeIn('300') 
}); 
$('#l1c').mouseout(function() { 
    $(this).fadeOut('300'); 
    $('#l1').fadeIn('300') 
}); 
$('#l2c').mouseout(function() { 
    $(this).fadeOut('300'); 
    $('#l2').fadeIn('300') 
}); 
$('#l3c').mouseout(function() { 
    $(this).fadeOut('300'); 
    $('#l3').fadeIn('300') 
}); 
$('#l4c').mouseout(function() { 
    $(this).fadeOut('300'); 
    $('#l4').fadeIn('300') 
}); 
$('#l5c').mouseout(function() { 
    $(this).fadeOut('300'); 
    $('#l5').fadeIn('300') 
}); 
$('#l6c').mouseout(function() { 
    $(this).fadeOut('300'); 
    $('#l6').fadeIn('300') 
}); 
$('#l7c').mouseout(function() { 
    $(this).fadeOut('300'); 
    $('#l7').fadeIn('300') 
}); 
+2

두 가지 유형의 div에 대해 두 개의 클래스를 추가 할 수 있습니까? 그렇게하면 훨씬 쉬울 것입니다. – sje397

+0

반복 패턴을 보았습니다. /// 그래서 클럽 코드 – kobe

답변

6
$('#l1,#l2,#l3,#l4,#l5,#l6,#l7').hover(function() { 
    $(this).fadeOut(300); 
    $("#" + this.id + "c").fadeIn(300); 
}); 

$('#l1c,#l2c,#l3c,#l4c,#l5c,#l6c,#l7c').mouseout(function() { 
    $(this).fadeOut(300); 
    $("#" + this.id.substring(0, this.id.length - 1)).fadeIn(300); 
}); 
+0

'this.id'를'$ (this) .attr ("id")', cf. [ "요소의 속성에 액세스하기위한 jQuery의 뛰어난 성능 활용"] (http://whattheheadsaid.com/2010/10/utilizing-the-awesome-power-of-jquery-to-access-properties-of-an -요소) – jensgram

1

당신은 DIV의 두 가지 유형의 두 가지 클래스를 추가 할 수 있습니다. 예 : # l1에서 # l7의 경우, 클래스 ".ln"을 추가하십시오. # l1c ~ # l7c의 경우 ".lnc"클래스를 추가 한 다음 아래 코드를 사용하십시오.

$(".ln").live("hover", function(){ 
    $(this).fadeOut('300'); 
    $("#" + $(this).attr("id") + "c").fadeIn(300); 
}; 

$(".lnc").live("mouseout", function(){ 
    var id = $(this).attr("id"); 
    $(this).fadeOut('300'); 
    $("#" + id.substring(0, id.length - 1)).fadeIn(300); 
}; 
관련 문제