突出显示具有相同类的所有 div

Posted

技术标签:

【中文标题】突出显示具有相同类的所有 div【英文标题】:highlight all divs with same class 【发布时间】:2013-08-14 17:10:18 【问题描述】:

所以我有一个包含 15 名团队成员 (.member) 的部分。如果我将鼠标悬停在设计团队的成员上,每个非设计成员都会获得 0.3 的不透明度。我到目前为止是这样的:

  // ENGINEERS
    $('.engineer').hover(function() 
        $('.member').not($('.engineer')).stop().animate(
            opacity: .3
        , 300);
    , function() 
        $('.member').stop().animate(
            opacity: 1
        );
    , 150);

  // DESIGNERS
    $('.designer').hover(function() 
        $('.member').not($('.designer')).stop().animate(
            opacity: .3
        , 300);
    , function() 
        $('.member').stop().animate(
            opacity: 1
        );
    , 150);

    // PRODUCT
    $('.product').hover(function() 
        $('.member').not($('.product')).stop().animate(
            opacity: .3
        , 300);
    , function() 
        $('.member').stop().animate(
            opacity: 1
        );
    , 150);

它可以工作,但是对于每个类别,您都必须添加一个新功能。这可能是一个菜鸟问题,但我可以统一这些功能吗?我尝试使用 .each(),但在选择所有其他成员并将它们淡出时我被卡住了。

【问题讨论】:

【参考方案1】:

像这样尝试this

$('.product , .designer , .engineer').hover(function() 
    $('.member').not($(this)).stop().animate( 
        opacity: .3
    , 300);
, function() 
    $('.member').stop().animate(
        opacity: 1
    );
, 150);

【讨论】:

【参考方案2】:

像Documentation这样使用多个选择器

$('.engineer, .designer, .product').hover(function () 
    $('.member').not($(this)).stop().animate(
        opacity: .3
    , 300);
, function () 
    $('.member').stop().animate(
        opacity: 1
    );
, 150);

【讨论】:

【参考方案3】:

你也可以试试

 $('.product , .designer , .engineer').on('hover', function() 
   $('.member').not($(this)).stop().animate( 
    opacity: .3
   , 300);
  , function() 
    $('.member').stop().animate(
    opacity: 1
   );
, 150);

【讨论】:

【参考方案4】:

html稍作重新设计即可解决问题

在标记中添加一个附加属性data-type,如下所示

<div class="member engineer" data-type="engineer">e4</div>

然后

var members = $('.member').hover(function() 
    members.filter('[data-type="' + $(this).data('type') + '"]').stop().animate(
        opacity: .3
    , 300);
, function() 
    members.filter('[data-type="' + $(this).data('type') + '"]').stop().animate(
        opacity: 1
    );
, 150);

演示:Fiddle

【讨论】:

以上是关于突出显示具有相同类的所有 div的主要内容,如果未能解决你的问题,请参考以下文章