繁体   English   中英

使用jQuery在悬停时添加CSS类

[英]Add CSS class on hover using jQuery

我正在尝试使用jQuery将鼠标悬停时添加CSS类到元素。 但是,该类仅应应用于特定类的最近元素,因此我尝试使用.next

当我将.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>

应该

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

要么

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

这是因为next()不在后代中,而是在下一个节点中。

您的问题是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');
});

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM