問題描述
將樣式作為參數傳遞給 jquery animate (passing style as argument to jquery animate)
所以我有一個處理懸停元素的功能,但是我希望能夠將 css 樣式作為參數傳遞。我嘗試了不同的變體,但這是我目前的代碼(只是必要的部分)......
function load_hovers(mouseOverCss){
$('.hover').hover(function(){
$(this).animate({
eval(mouseOverCss)
}, 500, function() {
});
我調用 load_hovers("backgroundColor: 'red'");
this 返回錯誤 invalid object initializer $(this).animate({< /code>。不使用
eval
,錯誤是 missing : after property id {eval(mouseOverCss)}\n
。
有什麼建議嗎?< /p>
## 參考解法 #### 方法 1: You're probably better to stay away from the Eval option (Eval is evil and all that...) and try passing in an object to your method instead.
First create an object for your CSS argument:
var css = {};
css.Property = 'backgroundColor';
css.Value = 'Red';
Then you can pass this (or an array of them, if you need multiple properties) to your method:
function load_hovers(classes)
{
$('.hover').hover(function(){
$(this).animate({
$(this).css(classes.Property, classes.Value); // or iterate over an array of these
}, 500, function() {
});
});
}
方法 2:
got it.
var mouseOverCss = {};
mouseOverCss['backgroundColor'] = 'red';
mouseOverCss['paddingLeft'] = '100px';
load_hovers(mouseOverCss);
and then just
$(this).animate(mouseOverCss, duration);
thanks Phil for getting me on the path of not just sending a string pre‑formatted for animate()!
(by brewster、Phil.Wheeler、brewster)
參考文件