2013-05-12 76 views
0

我已經創建了兩個函數,它們允許我將它們用於不同的CSS類。jquery函數不顯示動畫

var CSSElement; 
$(document).ready(function(){ 


    expandBox (".orange"); 
    minimizeBox(".orange"); 

}); 

function expandBox ($CSSElement){ 
    //When mouse rolls over 
    $($CSSElement).mouseover(function(){ 
     $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'}) 
    });  
} 

function minimizeBox ($CSSElement){ 
    //When mouse is removed 
    $(CSSElement).mouseout(function(){ 
     $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'}) 
    }); 
} 

但是,只有函數expandBox似乎工作。如果我將鼠標懸停在.orange元素上,那麼該框不會收縮。

我希望這些動畫顯示爲功能,因爲我打算在我的網站中多次使用它們。如果我把我的代碼如下:

$(document).ready(function(){ 

    //When mouse rolls over 
    $($CSSElement).mouseover(function(){ 
     $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'}) 
    }); 

    //When mouse is removed 
    $(CSSElement).mouseout(function(){ 
     $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'}) 
    }); 

}); 

一切似乎工作正常。第一個代碼不起作用,但第二個代碼有效的原因是什麼?

感謝,

vnayak

+1

能否請您提供一套完整的信息,即HTML和jQuery部分,也概括了它的jsfiddle? – 2013-05-12 22:50:05

回答

3

我想你犯了一個錯字:

$($CSSElement) 

$(CSSElement) 

這就是爲什麼它不工作

+0

感謝凱蒂!它現在完美。深夜編碼對我來說是件壞事,我想! – user2280642 2013-05-13 07:32:52

2

在JavaScript中,$是一個完全合法的字符標識符(而不是完全禁止[比如C]或特殊的簽名[PHP,Perl])。因此,$CSSElement是與CSSElement不同的標識符 - 如果只定義了一個,則另一個不起作用。 $($CSSElement)$(CSSElement)是不同的

(這可能造成混亂,與$前綴變量名;在JavaScript他們的工作不就好了。)

什麼是發生在這裏:

  1. 這兩個函數需要一個與$命名參數。
  2. expandBox將該參數與$一起使用。
  3. minimizeBox使用它沒有$(因此使用一些不相關的變量)。

我的建議是:改變一切不使用前綴$,像這樣:

function expandBox (CSSElement){ 
    //When mouse rolls over 
    $(CSSElement).mouseover(function(){ 
     $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'}) 
    });  
} 

function minimizeBox (CSSElement){ 
    //When mouse is removed 
    $(CSSElement).mouseout(function(){ 
     $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'}) 
    }); 
} 
+0

感謝Michaelb958的解釋。非常感激。 – user2280642 2013-05-13 21:12:50