我有一个mouseenter功能,将选定的div变成红色和1不透明度。我有一个类“完整”,只是这样做,但是当我在mouseenter中添加该类时,div不会更改颜色。相反,如果我添加红色并使用this.style.color和this.style.opacity更改mouseenter内部的不透明度,那么它似乎工作。我的问题是为什么?addClass()在mouseenter()中不起作用?
的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(WORKING):
$('.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'和'$(this)'之间的区别吗? – user2441391
'this'是指DOM元素,'$(this)'是封装在jquery对象中的DOM元素,并向其中添加了jquery方法。 'addClass()'是一个jquery的方法,这就是为什么你需要使用jquery对象。 –
这个指的是(在这个例子中)一个DOM节点。 '$(this)'返回一个基于'this'引用的节点的JQuery对象。 jquery对象具有$ function可以访问的所有方法。一个正常的dom节点不会。 –