jquery - 在 jQuery 中查找属于父类的类

标签 jquery html hover

尝试使用悬停移动一些 div,这是我的标记:

<div class="item dark-grey">
    <div class="img">
        <img src="images/case-study-develop.jpg" width="174" height="59" alt="Case Study">
    </div>
    <div class="triangle-container">
        <div class="triangle-border-light-blue"></div>
        <div class="triangle-dark-grey"></div>
    </div>
    <div class="content light-blue">
        <h2><a href="#">Developing community work with the voluntary sector</a></h2>
    </div>
</div>

这就是我目前正在使用的,效果很好,但我只想将鼠标悬停在内容 div 上,而不是整个项目 div 上。

$(document).ready(function() {
            $('.item').hover(function(e){
                    $('.img', this).animate({height: "30px"},100);
            },function(e){
                    $('.img', this).animate({height: "58px"},100);
            });
    });

我想如果我将鼠标悬停在 .item .content 上,然后获取父项,并找到属于父项的 .img ,它就会起作用,但不确定我是否做得正确。

$('.item .content').hover(function(e){
                $(this).parents('.img').animate({height: "30px"},100);
}

最佳答案

您所拥有的内容将不起作用,因为 .img 不是 .content 的父级,它是同级。

您可以检查.content()siblings():

$('.item .content').hover(
    function(e){
        $(this).siblings('.img').animate({ height: "30px" }, 100);
    },
    //function...
});

或者您可以向上遍历 DOM 到 .content 的父级,然后 find('.img'):

$('.item .content').hover(
    function(e){
        $(this).parent().find('.img').animate({ height: "30px" }, 100);
    },
    //function...
});

或者如果你能保证这些div的结构永远不会改变,你可以使用prev():

$('.item .content').hover(
    function(e){
        $(this).prev().prev().animate({ height: "30px" }, 100);
    },
    //function...
});

关于jquery - 在 jQuery 中查找属于父类的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9995401/

相关文章:

javascript - 如何给两个交替的背景图像?

php - Mysql数组数据不显示表格

jquery - 在 bootstrap 日期选择器中突出显示整个 <tr> 周

html - <a> 中的图像在应用悬停效果后不起作用

jQuery 对话框 - 未定义

jquery - 如何在jquery数据表中动态显示列标题

html - div的位置放在FORM旁边

css - 如何在悬停在下拉菜单上时使列表项保持事件状态?

php - 第二次更新 2 个表未使用 Ajax 更新

javascript - 使用键数组过滤对象数组[逆]