简体   繁体   English

悬停时删除和添加类

[英]Removing and adding class on hover

I am making a panel of photos/text. 我正在制作一组照片/文字。 All the panels will have an overlay color on them except the first one which has an active class on page load which removes the overlay. 除了第一个面板在页面加载时具有活动类之外,所有面板上都将具有叠加层颜色,从而删除该叠加层。 As you hover over the second/third etc panels, the overlay active class will remove from first panel and go onto the one that is hovered. 当您将鼠标悬停在第二个/第三个etc面板上时,覆盖层活动类将从第一个面板上删除,然后转到被悬停的那个类上。

Right now it is only active on page load, I can't seem to get the class off the first div and onto the second div on hover. 现在,它仅在页面加载时有效,我似乎无法将类从第一个div移到第二个div上。

if ( $(".overlay:first") ){
     $(".overlay:first").addClass("active");
     }

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

       }    

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

There is no need to use JavaScript or jQuery for this. 无需为此使用JavaScript或jQuery。 It's best used in CSS with the :hover pseudo-selector. 最好在CSS中使用:hover伪选择器。 It's also much easier today. 今天也要容易得多。

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

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

If you insist on using jQuery, you can try this 如果您坚持使用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> 

This approach is highly frowned upon though 这种方法虽然不被接受

In jQuery, you could do it like this: 在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");
  });

});

but Richard Hamilton's answer is much better and cleaner. 但理查德·汉密尔顿(Richard Hamilton)的答案更好,更干净。

You can use jQuery's on . 您可以on使用jQuery。 For example: 例如:

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

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

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