简体   繁体   English

jQuery函数在按钮悬停时从div添加/删除类

[英]Jquery function add/remove class from div on button hover

I have this jquery script that I got some help with in creating in order to add/remove an "active" class to a div when hovering over a button. 我有这个jquery脚本,在创建时得到了一些帮助,以便将鼠标悬停在div上时将“活动”类添加到div中或从中删除。

Below a CodePen of what I have put together: 下面是我放在一起的CodePen:

CodePen Link : https://codepen.io/dustin-keeslar/pen/dapLWM CodePen链接https : //codepen.io/dustin-keeslar/pen/dapLWM

It works well, however what I'm trying to change is to have whatever button was last hovered on, to keep the "active" class on the content. 它运作良好,但是我要更改的是将最后一个按钮悬停在上面,以保持内容上的“活动”类。 So that the content only changes when a different button is hovered over. 因此,只有将鼠标悬停在其他按钮上时,内容才会更改。

jQuery(document).ready(function() {

  jQuery(".toggle-button").hover(function() {
    var target = jQuery(this).data("target");

    if (jQuery(this).hasClass("expand")) {
      jQuery(this).toggleClass("expand");

      jQuery("#" + target).removeClass("active");
    } else {
      jQuery(".toggle-button").removeClass("expand");
      jQuery(".hidden-content").removeClass("active");

      jQuery(this).toggleClass('expand');

      jQuery("#" + target).toggleClass("active");
    }

  });
});

This will find a button that has data-target=content1" for example, and when it is hovered over it will toggle an "active" class to a div with the ID "content1". The problem is that when you are no longer hovering, everything disappears. I need the most recent hovered button to keep the "active" class on the content. But I also need the content to change dynamically when the next button is hovered over. 例如,这将找到一个具有data-target=content1"的按钮,并将其悬停在其上时会将“活动”类切换为ID为“ content1”的div。问题在于,当您不再悬停时,一切都消失了。我需要使用最新的悬停按钮来保持内容上的“活动”类,但是当下一个按钮悬停时,我还需要动态更改内容。

Then fix it to use mouseenter, and move your remove code to the top to remove your classes before adding them back to the element that's been entered. 然后修复它以使用mouseenter,然后将删除代码移至顶部以删除类,然后再将其添加回输入的元素中。 I don't understand exactly what you're trying to do here, but using mouseenter it should be something like: 我不完全知道您要在这里做什么,但是使用mouseenter应该是这样的:

jQuery(document).ready(function() {

jQuery(".toggle-button").mouseenter(function() {
  jQuery(".toggle-button").removeClass("expand");
 //      jQuery(".hidden-content").removeClass("active");
  $(".active").removeClass("active");
  var target = jQuery(this).data("target");
  jQuery("#" + target).addClass("active");

  if (jQuery(this).hasClass("expand")) {
    jQuery(this).removeClass("expand");

    jQuery("#" + target).removeClass("active");
  }

});
}); 

All you are missing is a check, to ensure the current item matches the target: 您所缺少的只是一项检查,以确保当前项目与目标匹配:

 jQuery(this).attr('id') == target

Codepen here: https://codepen.io/anon/pen/VgKOPy 此处的Codepen: https ://codepen.io/anon/pen/VgKOPy

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

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