使鼠标悬停在一个类上影响页面上所有相同类的其他类

Make hover over one class affect all other of same class on page

本文关键字:其他 同类 影响 鼠标 一个 悬停      更新时间:2023-09-26

我希望在子导航中使悬停在列表项上,激活页面上该类别中所有项的类(不仅仅是父类或兄弟元素)。什么好主意吗?下面是我的意思的一个例子:

<style>
img.BLUE {border:1px solid #FFF}
</style>
<ul id="subnav">
<li id="BLUE">Blue</li> <!--When hovering these...-->
<li id="PINK">Pink</li>
<li id="YELLOW">Yellow</li>
</ul>
<!--other stuff here-->
<img class="BLUE" href="image.jpg"> <!--it applies the border to this and any other img.blue on the page-->
<img class="PINK" href="image1.jpg">
<img class="YELLOW" href="image2.jpg">

这应该是你想要的。

<style type="text/css">
   img.active{border:1px solid #FFF;}
</style>

$('#subnav li').hover(function(){
  $('.' + this.id).addClass('active');
},function(){
  $('.' + this.id).removeClass('active');
});

DEMO

$('#subnav li').hover(function(){
    var id = $(this).attr('id');                     // grab ID of clicked el
    $('img.'+id).css({border: '1px solid #fff'});    // image class=IDname : add CSS prop.
});