在悬停时添加和删除 CSS 类

add and remove css class on hover

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

所以我有这段代码,它可以工作:

$('.col-main').on('mouseenter', '.product-wrapper', function () {
  $( this ).addClass( "js-hover" );
});
$('.col-main').on('mouseleave', '.product-wrapper', function () {
  $( this ).removeClass( "js-hover" );
});

但我希望它更优雅一点。像这样:

listContainer.on( {
  mouseenter: function() {
    $( this ).addClass( "js-hover" );
    console.log( "hoooover" );
  },
  mouseleave: function() {
    $( this ).removeClass( "js-hover" );
  }
}, productWrapper );

但我无法让它工作:)任何帮助不胜感激

我认为问题出在变量productWrapper。尝试像跟随一样。

var listContainer=$('.col-main')
var productWrapper='.product-wrapper';
listContainer.on( {
    mouseenter: function() {
        $( this ).addClass( "js-hover" );
        console.log( "hoooover" );
    },
    mouseleave: function() {
        $( this ).removeClass( "js-hover" );
   }
}, productWrapper );

像这样吗?

$('.col-main').on('mouseenter mouseleave', '.product-wrapper', function (e) {
    $( this ).toggleClass( 'js-hover', e.type === 'mouseenter');
});

jQuery悬停和切换函数可能对你有用。

$('.element-selector').hover(function(){   
  $(this).toggleClass('.class-to-toggle');
}, function(){
  $(this).toggleClass('.class-to-toggle');
})

小提琴:https://jsfiddle.net/sdso2219/

更新


由于您现在提到这需要适用于动态元素,请将 .hover 修改为 .live,例如:

$('.element-selector').live('mouseenter', function(){   
  $(this).toggleClass('.class-to-toggle');
}).live('mouseleave', function(){
  $(this).toggleClass('.class-to-toggle');
})