2009-12-09 99 views
0

我正在爲我的網站使用基於JQuery的css菜單。然而,我的問題是如果我點擊一個菜單項。我希望它保持一種顏色,在我的情況下是一半的圖像。菜單項處於活動狀態時出現JQuery CSS菜單問題

我從http://snook.ca/archives/javascript/jquery-bg-image-animations/得到我的代碼我用第二個例子。繼承人的示例頁面:http://snook.ca/technical/jquery-bg/

我的代碼如下

<script type="text/javascript"> 
     $(function(){ 

     $('#nav a') 
      .css({backgroundPosition: "-20px 35px"}) 
      .mouseover(function(){ 
       $(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:800}) 
     }) 
      .mouseout(function(){ 
       $(this).stop().animate({backgroundPosition:"(40px 35px)"}, {duration:800, complete:function(){ 
        $(this).css({backgroundPosition: "-20px 35px"}) 
       }}) 


     }) 
     }); 
    </script> 

如果你將鼠標懸停在菜單中的菜單將變成不同的顏色,這就是我想要留在菜單時,菜單顏色活躍並已被點擊。

希望有人能幫助我。

我想作爲回答說,仍然沒有

我修改後的代碼

<script type="text/javascript"> 
    $(function(){ 

    $('#nav a') 
     .css({backgroundPosition: "-20px 35px"}) 
     .mouseover(function(){ 
      $(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:800}) 
    }) 
     .mouseout(function(){ 
      $(this).stop().animate({backgroundPosition:"(40px 35px)"}, {duration:800, complete:function(){ 
       $(this).css({backgroundPosition: "-20px 35px"}) 
      }}) 


    }) 

    $('#nav a').click(function() { 
     $('#nav a:not(.selected'); 
     $('#nav a').removeClass('selected'); 
     $(this).addClass('selected'); 
    }) 


    }); 



</script> 

回答

2

您應該添加CSS類的被點擊的鏈接,不象這樣:

$('#nav a').click(function() { 
    $('#nav a').removeClass('selected'); 
    $(this).addClass('selected'); 
}) 

然後,你可以有一個CSS聲明,如:

.selected { background-position: -20px 35px; } 

最後,如果您不希望覆蓋CSS,則應將mouseOver和mouseOut函數設置爲$('#nav a:not(.selected')

[編輯] 下面是完整的代碼:

$(function(){ 

    $('#nav a:not(.selected)') 
     .css({backgroundPosition: "-20px 35px"}) 
     .live('mouseover', function(){ 
      $(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:800}) 
     }) 
     .live('mouseout', function(){ 
      $(this).stop() 
       .animate({ 
        backgroundPosition:"(40px 35px)"}, 
        {duration:800, complete:function(){ 
         $(this).css({backgroundPosition: "-20px 35px"}); 
       }}) 
    }) 

    $('#nav a') 
     .live('click', function() { 
      $('#nav a').removeClass('selected'); 
      $(this).addClass('selected'); 
     }); 
}); 
+0

@Alex,請將鼠標懸停和鼠標移至live()事件上,我會給你一個+1 –

+0

我試過但不知何故似乎不起作用 我在我的答案的底部添加了我的代碼 – Roland

+0

@cballou:完成! @Roland:請試試我發佈的完整代碼示例 –

1

隨着亞歷山大的代碼添加一個選擇的類時,項目選擇,你應該能夠修改鼠標了監聽器,像這樣:

.mouseout(function(){ 
    // cache $(this) rather than executing it multiple times 
    var $this = $(this); 
    if (!$this.is('.selected')) { 
     $this.stop().animate(
      { 
       backgroundPosition:"(40px 35px)" 
      }, 
      { 
       duration:800, 
       complete:function() 
       { 
        $this.css({backgroundPosition: "-20px 35px"}) 
       } 
      } 
    ) 
}) 

希望它有幫助!

相關問題