2010-03-25 97 views
1

我有一個由以下HTML組成的簡單導航欄;移動到下一個菜單項時刪除課程

<div class="inner"> 
<div class="button"><img class="portal" src="images/portalbutton.png" /></div> 
<a href="#"><div class="prod_description">&nbsp;</div></a> 
</div> 

有一些項目(所有設置左邊浮動彼此)組成一個導航欄。

當我將鼠標懸停在.button和/或.prod_description我想.inner<div>有類.hover添加到它。這樣我就可以在整個事物上設置一個背景圖像(有點像突出顯示導航項目)。

我只想刪除.hover,而另一個.button or .prod_description被移走,在這種情況下,此導航項採用.hover類。

+0

爲什麼不直接設置.inner div的背景下,當你將鼠標懸停在.button或.prod_description?爲什麼你需要將.hover添加到.inner? – Lazarus 2010-03-25 16:22:33

+0

在這種情況下,只有當我將鼠標懸停在另一個.inner上時,我怎樣才能刪除背景? – CLiown 2010-03-25 16:26:34

回答

2

當我將鼠標懸停在.button和/或.prod_description我想.inner<div>有類.hover添加到它。

除非你的CSS是以一種非常聰明的方式定位事物,否則這與徘徊.inner本身是一樣的吧?如果是這樣,該任務可以解決了一樣容易:

$('.inner').hover(function() { 
    $('.inner').removeClass('hover'); 
    $(this).addClass('hover'); 
}); 

如果我的上述定位假設不成立,該代碼將不得不尋找更多這樣的:

$('.inner .button, .inner .prod_description').hover(function() { 
    $('.inner').removeClass('hover'); 
    $(this).parents('.inner').addClass('hover'); 
}); 

在後面代碼示例,請注意使用parents() - 不要與parent()混淆。

+0

不錯,簡單,並減少了代碼。使用第二個選項。 – CLiown 2010-03-26 09:22:54

1

有了這個小改變你的HTML,JavaScript的將是一個比較容易寫:

<div class="inner"> 
    <div class="button"><img class="portal" src="images/portalbutton.png" /></div> 
    <div class="prod_description"><a href="#">stuff</a></div> 
</div> 

然後,你Javscript功能看起來是這樣的。當您懸停一個項目時,它會從所有項目中移除hover類,並將其應用於當前項目。那樣的話,hover班將會留下,即使離開物品。

$(document).ready(function() { 
      $('div.button, div.prod_description').mouseover(function() { 
       $('div.inner').removeClass('hover'); 
       $(this).parent().addClass('hover'); //The HTML change was to allow the call to parent() to be the same 
      }); 
     }); 
2

試試這個:

$(document).ready(function(){ 
    $(".button").hover(
    function() { 
     $(".inner").removeClass("hover"); 
     $(this).parent(".inner").addClass("hover"); 
    }, 
    function() {} 
); 
$(".prod_description").hover(
    function() { 
     $(".inner").removeClass("hover"); 
     $(this).parent("a").parent("inner").addClass("hover"); 
    }, 
    function() {} 
); }); 
+0

究竟需要什麼,複製和粘貼賓果! – CLiown 2010-03-25 16:41:21

+0

此外,這是很多不必要的重複代碼;) – 2010-03-25 16:42:27

+0

你能讓以上更好嗎? – CLiown 2010-03-25 16:44:23