悬停时删除和添加类

Removing and adding class on hover

本文关键字:添加 删除 悬停      更新时间:2023-09-26

我正在制作一组照片/文字。所有面板上都有一个覆盖颜色,除了第一个在页面加载时有一个活动类,它会删除覆盖。当您将鼠标悬停在第二个/第三个等面板上时,覆盖活动类将从第一个面板中删除并转到悬停的面板。

现在它仅在页面加载时处于活动状态,我似乎无法在悬停时将类从第一个div 转移到第二个div。

if ( $(".overlay:first") ){
     $(".overlay:first").addClass("active");
     }
else {
    if ( $(".overlay:not(:first)").hover ){
           $(".overlay:first").removeClass("active");
          }
       }    

https://jsfiddle.net/egdkuh16/3/

没有必要为此使用 JavaScript 或 jQuery。它最好在带有:hover伪选择器的 CSS 中使用。今天也容易多了。

.overlay:first-child {
   background: white;
}
.overlay:first-child:hover {
  background: gold;
}

如果你坚持使用jQuery,你可以试试这个

$(".overlay:first").on("mouseover", function() {
    $(this).addClass("active");
}).on("mouseout", function() {
    $(this).removeClass("active");
});
.active {
  background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overlay">First overlay class</div>
<div class="overlay">Second overlay class</div>

这种方法非常不受欢迎

在jQuery中,你可以这样做:

$(document).ready(function() {
  // Make the first active
  $(".overlay:first").addClass("active");
  // On hover remove all active classes from .overlay
  // and add .active only to the one that is hovered
  $(".overlay").hover(function() {
    $(".overlay").removeClass("active");
    $(this).addClass("active");
  });
});

但理查德·汉密尔顿的答案要好得多,也干净得多。

你可以

使用 jQuery 的on 。例如:

$(".overlay:first").addClass("active");
$(".overlay").on("hover", function(){
    $(this).addClass("active");
    $(".overlay:first").removeClass("active")
});