2011-01-13 25 views
1

這裏的回調函數不起作用。我想我錯誤地使用了startColor變量。錯誤地嵌入jQuery變量

注意:這需要jQuery UI。

$("a").hover(function() { 
    var startColor = $(this).css("color"); 
    $(this).stop().animate({ color: "#54a888"}, 350); 
    },function() { 
    $(this).stop().animate({ color: " + startColor + "}, 350); 
}); 

謝謝你們。我其實是想重構這個代碼:

$("nav ul li a, aside ul li a").hover(function() { 
    $(this).stop().animate({ color: "#54a888"}, 350); //End color 
    },function() { 
    $(this).stop().animate({ color: "#5944b2"}, 350); //Start color 
}); 
$("h5#logo a, button").hover(function() { 
    $(this).stop().animate({ backgroundColor: "#54a888"}, 350); 
    },function() { 
    $(this).stop().animate({ backgroundColor: "#000000"}, 350); 
}); 
    $("h3 a").hover(function() { 
    $(this).stop().animate({ color: "#54a888"}, 350); 
    },function() { 
    $(this).stop().animate({ color: "#000000"}, 350); 
}); 

我有不同的起始顏色和不同的性質,我想動畫。似乎有比重複相同的代碼3次更好的解決方案。

+0

請原諒我的壞格式 – DaveKingsnorth 2011-01-13 21:25:55

+0

我不是一個jQuery專家,但你沒有在你剛剛發佈的內容中使用`startColor`變量 - 你只需要確切的字符串`「+ startColor +」` – 2011-01-13 21:27:26

回答

1

聲明這兩項功能外,並刪除" + + "

var startColor; 

$("a").hover(function() { 
    startColor = $(this).css("color"); 
    $(this).stop().animate({ color: "#54a888"}, 350); //End color 
},function() { 
    $(this).stop().animate({ color: startColor}, 350); //Start color 
}); 

...或者更好的是,使用.data()記得那個特定元素的顏色:

$("a").hover(function() { 
    if(!$(this).data('startColor')) { 
     $(this).data('startColor', $(this).css("color")); 
    } 
    $(this).stop().animate({ color: "#54a888"}, 350); //End color 
},function() { 
    $(this).stop().animate({ color: $(this).data('startColor')}, 350); 
}); 

...或者如果所有鏈接的顏色恰好相同,只需獲取一次,然後重新使用該值即可。由於您正在處理動畫,因此實際上可能會更安全。

var startColor = $(a).css("color"); 

$("a").hover(function() { 
    $(this).stop().animate({ color: "#54a888"}, 350); //End color 
},function() { 
    $(this).stop().animate({ color: startColor}, 350); //Start color 
}); 

編輯:基於更新後的問題,它看起來就像你正在試圖做一些代碼減少。看起來他們之間有足夠的差異,試圖整合會變得複雜,以至於你可能會得到更多的代碼。

一個減少的辦法是改變你的hover()處理程序接受1個功能,而不是2:

$("h3 a").hover(function(e) { 
    $(this).stop().animate({ color: e.type == 'mouseenter' ? "#54a888" : "#000000"}, 350); 
}); 

縮短了一陣。

另一個選擇(因爲你使用jQueryUI我假設)將動畫toggleClass(雖然我認爲它可能會在最新版本的UI中被破壞)。

$("h3 a,nav ul li a, aside ul li a,nav ul li a, aside ul li a").hover(function(e) { 
    $(this).stop().toggleClass('hover', 350); 
}); 
在CSS

然後:

h3 a.hover { 
    color:#000000; 
} 

nav ul li a.hover, aside ul li a.hover { 
    color:#54a888; 
} 

// etc... 

...只是知道再次,我認爲它可能在最新的版本被破碎之後,你需要測試,因爲它有時古怪。

1

" + + "沒有意義。只需使用

$(this).stop().animate({ color: startColor}, 350); //Start color }); 
0

您正在一個回調中創建一個局部變量,並試圖在另一個回調中使用它。

相反,您應該使用$.data存儲舊顏色。
另外,不要在變量周圍加引號;這使它成爲一個字符串。