addClass()在mouseenter()中不起作用

addClass() not working in mouseenter()?

本文关键字:不起作用 addClass mouseenter      更新时间:2023-09-26

我有一个mouseenter函数,它将选定的div变成红色和1不透明度。我有一个类"full",它就是这样做的,但当我在mouseenter中添加该类时,div不会改变颜色。相反,如果我添加红色,并用this.style.color和this.style.opacity更改鼠标中心内的不透明度,那么它似乎可以工作。我的问题是为什么?

jquery(不工作):

$('.content').mouseenter(function() {
    $( ".content" ).each(function (i) {
        if ( this.style.color != "#F7F7F7" ) {
            this.style.color = "#F7F7F7";
            this.style.opacity = "0.5";
        }
    });
    this.addClass('full');
}); 

jquery(正在工作):

$('.content').mouseenter(function() {
    $( ".content" ).each(function (i) {
        if ( this.style.color != "#F7F7F7" ) {
            this.style.color = "#F7F7F7";
            this.style.opacity = "0.5";
        }
    });
    this.style.color = "red";
    this.style.opacity = "1";
});

CSS:

.full 
{
color: red;
opacity: 1;
}

this不是mouseenter方法回调中的jquery集合。您需要使用$(this)

有几个问题;一个是this不是处理程序中的jQuery对象。另一个是您的style规则将始终优先于类*。我真的不知道上下文是什么,但似乎你应该默认地让它们都是那样的颜色,并添加和删除类:

var $content = $('.content');
$content.mouseenter(function() {
    $content.removeClass('full');
    $(this).addClass('full');
}); 

尽管让你的CSS看起来应该少.full,多:hover,根本没有JavaScript。(这是最好的JavaScript。)

*没有!important,您永远不应该使用它

this应该像jQuery(this)一样使用。

用途:

$('.content').mouseenter(function() {
  $( ".content" ).each(function (i) {
    if ( this.style.color != "#F7F7F7" ) {
        this.style.color = "#F7F7F7";
        this.style.opacity = "0.5";
    }
  });
  jQuery(this).addClass('full');
}); 

您正在使用javascript设置内联样式。这些总是会否决类样式。