2013-01-11 20 views
0

正在使用一點javascript來爲div類中的類設置動畫。JQuery整理代碼

$(".previouscontainer").mouseenter(function(){ 
    $("a.previousarrow").animate({left:'0px'},"fast"); 
    }); 
$(".previouscontainer").mouseleave(function(){ 
    $("a.previousarrow").animate({left:'10px'},"fast"); 
    }); 
$(".nextcontainer").mouseenter(function(){ 
    $("a.nextarrow").animate({right:'0px'},"fast"); 
    }); 
$(".nextcontainer").mouseleave(function(){ 
    $("a.nextarrow").animate({right:'10px'},"fast"); 
    }); 

想知道是否有更好的/更清潔的方式來寫這個?

+0

你應該包括相關的HTML。 – Stefan

+0

這個問題的HTML不需要 – Popnoodles

+0

只要認爲'a.nextarrow'可能是'.nextcontainer'的子元素,'$(this).find(「a.nextarrow」)'可能是有用的... 沒關係。 – Stefan

回答

2

您可以鏈接它們。

$(".previouscontainer").mouseenter(function(){ 
    $("a.previousarrow").animate({left:'0px'},"fast"); 
    }).mouseleave(function(){ 
    $("a.previousarrow").animate({left:'10px'},"fast"); 
    }); 
$(".nextcontainer").mouseenter(function(){ 
    $("a.nextarrow").animate({right:'0px'},"fast"); 
    }).mouseleave(function(){ 
    $("a.nextarrow").animate({right:'10px'},"fast"); 
    }); 

或使用懸停這需要兩個功能

$(".previouscontainer").hover(function(){ 
    $("a.previousarrow").animate({left:'0px'},"fast"); 
    },function(){ 
    $("a.previousarrow").animate({left:'10px'},"fast"); 
    }); 
$(".nextcontainer").hover(function(){ 
    $("a.nextarrow").animate({right:'0px'},"fast"); 
    },function(){ 
    $("a.nextarrow").animate({right:'10px'},"fast"); 
    }); 

或者,如果你需要將其綁定到不同的動作,你可以去瘋狂和創建自己的事件

$("a.previousarrow").on('moveme', function(){ 
    if ($(this).css('left')>0) $(this).animate({left:'0px'},"fast"); 
    else $(this).animate({left:'10px'},"fast"); 
}); 

,可以」 t在同一個選擇器中

$(".previouscontainer").on('mouseover mouseleave', function(){ 
    $("a.previousarrow").trigger('moveme'); 
}); 

$('#somethingelse').on('click', function(){ 
    $("a.previousarrow").trigger('moveme'); 
}); 

還有其他方法可以擺動這隻貓。 .hover()是最明智的。

+0

真棒 - 謝謝你 – Palemo

+1

我可以建議改善這個答案:考慮「緩存」選擇器,以減少負載。 –

+0

我不確定這會有幫助 – Popnoodles

0

您也可以使用.on()函數。

例1個箭頭

$(".previouscontainer").on({ 
    mouseenter: function(){ 
    $("a.previousarrow").animate({left:'10px'},"fast"); 
    }, 
    mouseleave: function(){ 
    $("a.previousarrow").animate({left:'0px'},"fast"); 
    } 
});