2011-06-20 38 views
-2

我嘗試添加點擊功能,但它不能運行......如何結合了懸停功能相同的狀態點擊

$("#menu2 li").hover(function() { //On hover... 

    $(this).find("span").stop().animate({ 
     marginTop: "-40" //Find the span tag and move it up 40 pixels 
    }, 250); 

    $("#menu2 li").click(function() { //On click... 
     $(this).find("span").stop().animate({ 
      marginTop: "-40" //Find the span tag and move it up 40 pixels 
     }, 250); } 
     , function() { //On hover out... 
      $(this).find("span").stop().animate({ 
       marginTop: "0" //Move the span back to its original state (0px) 
      }, 250); 
     }); 
}); 

這裏是鏈接:after click, i hope it still be white color

+2

有什麼問題嗎? –

+1

你能解釋一下你想做什麼嗎?你想執行'mouseenter'(懸停)執行的相同函數嗎? –

+1

請點擊菜單中的更具體的 –

回答

2

更新:看到你的鏈接和閱讀的解釋之後,我會做這種方式:

創建CSS類selected

.selected span { 
    marginTop: "-40"; 
} 

的類添加到元素上點擊且僅當未選擇部件執行mouseleave動作:

$("#menu2 li").click(function() { 
    if(!$(this).hasClass('selected')) { 
     $(this).siblings('.selected').removeClass('selected').mouseleave(); 
     $(this).addClass('selected'); 
    } 
}).hover(function() { 
    $(this).find("span").stop().animate({ 
     marginTop: "-40" //Find the span tag and move it up 40 pixels 
    }, 250); 
}, function() { 
    if(!$(this).hasClass('selected')) { 
     $(this).find("span").stop().animate({ 
      marginTop: "0" //Move the span back to its original state (0px) 
     }, 250); 
    } 
}); 

我爲您建立一個DEMO


老答案:

這也許應該是:

function mouseEnterHandler { 
    $(this).find("span").stop().animate({ 
     marginTop: "-40" //Find the span tag and move it up 40 pixels 
    }, 250); 
} 

function mouseLeaveHandler() { 
    $(this).find("span").stop().animate({ 
     marginTop: "0" //Move the span back to its original state (0px) 
    }, 250); 
} 

$("#menu2 li").click(mouseEnterHandler) 
       .hover(mouseEnterHandler, mouseLeaveHandler); 
+0

so coooooool!非常感謝Felix Kling,你幫了我很多〜這就是我想要的。 – redleaf

3

我認爲你是在談論結合兩者的懸停和點擊在一起。試試這個:

$('#menu2 li').bind('click hover', function(){ 

// do stuff 

}); 
+0

這很整齊,我會創建一個單獨的函數並使用標準點擊和懸停apis將其綁定,但這樣更好。不知道我們可以做到這一點。 +1( –

+1

-1)'$('sel')。bind('hover',function(){/*...*/})'不起作用(對於所有想知道的人:http:// jsfiddle。淨/ fkling/jfHxj /)。而且,即使它與'$('sel').hover(in)'而不是'$('sel')相同。hover(in,out)' –