2016-07-27 30 views
0

我試圖在懸停到使用jQuery的元素上添加CSS類。然而,類應該只讓我嘗試使用.next使用jQuery在懸停上添加CSS類

當我加入.next我的代碼,雖然該類不再添加應用到最接近的元素與特定的類(它的工作原理沒有那部分代碼)。這是代碼:

$j('.products_overlay').hover(function(){ 
    $j(this).next('.hover_text').addClass('overlay_text'); 
}, function(){ 
    $j(this).next('.hover_text').removeClass('overlay_text'); 
}); 

任何想法我做錯了什麼?

這是HTML

<div class="products_overlay"> 
    <a href="..." title="product1" class="product-image"> 
     <img src="...." alt="product1" class="hover_test" /> 
    </a> 
    <p class="hover_text">Test</p> 
</div> 
+3

你的HTML,好嗎? – nicael

+0

某些片段或小提琴? – RaV

+1

聽起來像'.hover_text'不是'.products_overlay'的兄弟,所以'next()'不會找到它。我們需要看到你的HTML能夠幫助你修復這個 –

回答

0

jQuery代碼不工作作爲next()看着兄弟姐妹,但.hover_text.products_overlay一個孩子。因此,您應該使用find()。您也可以縮短使用toggleClass()代碼:

$j(function($) { 
    $('.products_overlay').hover(function(){ 
     $(this).find('.hover_text').toggleClass('overlay_text'); 
    }); 
}); 

話雖這麼說,鑑於你的HTML你不需要使用jQuery的。你可以實現你獨自CSS需要什麼:

.products_overlay:hover p { 
 
    color: red; /* place the relevant hover styling in here */ 
 
}
<div class="products_overlay"> 
 
    <a href="..." title="product1" class="product-image"> 
 
    <img src="...." alt="product1" class="hover_test" /> 
 
    </a> 
 
    <p class="hover_text">Test</p> 
 
</div>

1

應該

$j('.products_overlay .hoverText').addClass('overlay_text'); 

$j(this).find(".hoverText").addClass('overlay_text'); 

這是因爲next()不會在後人的樣子,但在下一個節點。

1

你的問題是next只發現姐弟

$j('.products_overlay').hover(function(){ 
    $j(this).next('.hover_text').addClass('overlay_text'); 
}, function(){ 
    $j(this).next('.hover_text').removeClass('overlay_text'); 
}); 

this在這種情況下是products_overlay DIV,所以你.hover_text是一個孩子,而不是一個兄弟姐妹。

要修復它使用find

$j('.products_overlay').hover(function(){ 
    $j(this).find('> .hover_text').addClass('overlay_text'); 
}, function(){ 
    $j(this).find('> .hover_text').removeClass('overlay_text'); 
}); 
+0

工作 - 謝謝! – MariaL

+0

歡迎:) –