2012-01-10 52 views
0

我有一个jQuery效果,如果用户将鼠标放在回复图像上,图像将更改为其他图像。我遇到的问题是,当您将鼠标悬停在另一个对象上,该对象设置为addClass()作为回复图像时,此新回复图像在鼠标悬停时不会更改其图像。jQuery - addClass()mouseover

我的问题的演示: http://www.sfu.ca/~jca41/stuph/jQueryTest/jQueryTest.html

$(document).ready(function(){ 

    $(".red").mouseover(function() { 
     $(this).css("color","red"); 
     $(this).addClass("reply"); 
    }); 
    $(".red").mouseout(function() { 
     $(this).css("color","black"); 
     $(this).removeClass("reply"); 
    }); 

    $(".reply").mouseover(function() { 
     $(this).css("background-image", "url(reply_h.png)"); 
    }); 
    $(".reply").mouseout(function() { 
     $(this).css("background-image", "url(reply.png)"); 
    }); 

}); 
+0

*注:*您应该链您的jQuery语句,如下所示:'$(this).css(“color”,“black”)。removeClass(“reply”);' – 2012-01-10 19:10:58

+0

很酷。不知道你能做到这一点。刚做了修改。谢谢:) – Jon 2012-01-10 19:12:53

回答

1

“新” 的回复图像是CSS背景的一部分。因此它实际上并不是DOM的一部分,因此jQuery无法修改它,甚至无法检测它何时被挖空。

为了得到你想要的结果,你需要做的DOM的第二按键部和隐藏/显示它来代替:http://jsfiddle.net/mblase75/tJwUW/3/

HTML:

Mouseover the reply image and it changes states 
<div class="reply"></div> 

<hr><hr><hr> 

<div class="red"> 
<div class="reply"></div> <!-- added --> 
Mouseover this, then mouseover the new reply image 
and notice it does not change state 
</div> 

CSS:

.reply { 
    background-image:url('reply.png'); 
    height: 18px; 
    background-repeat: no-repeat; 
} 
.red .reply { /* added */ 
    visibility: hidden; 
} 

JS:

$(".red").mouseover(function() { // modified 
    $(this).css("color", "red").find(".reply").css('visibility','visible'); 
}); 
$(".red").mouseout(function() { // modified 
    $(this).css("color", "black").find("reply").css('visibility','hidden'); 
}); 

$(".reply").mouseover(function() { 
    $(this).css("background-image", "url(reply_h.png)"); 
}); 
$(".reply").mouseout(function() { 
    $(this).css("background-image", "url(reply.png)"); 
}); 
+0

在这种情况下,我可能的解决方案是什么?我应该使用某种innerHTML策略吗? – Jon 2012-01-10 19:17:58

+0

很酷。从未想过使用可见性:隐藏。整洁的把戏:) – Jon 2012-01-10 19:39:31

+0

有一个我注意到的错误。当你弹出时,回复图像不会消失。 – Jon 2012-01-10 19:50:24

0

为什么在mouseover上添加鼠标悬停的事件来更改bg-image? 直接在.red的鼠标悬停来更改图像时不会更容易吗?

0

它的原因是,当您将鼠标悬停在class'red'的div上时,'reply'类会添加到它,并且它也处于鼠标悬停状态。

解决方案:跟上类 '红色' 的DIV中空白格文本之前:

<div class="red"><div></div>demo text</div> 

和修改你的脚本

$(".red").mouseover(function() { 
    $(this).css("color","red"); 
    $(this).children('div').addClass("reply"); 
}); 
$(".red").mouseout(function() { 
    $(this).css("color","black"); 
    $(this).children('div').removeClass("reply"); 
}); 

$(".reply").mouseover(function() { 
    $(this).css("background-image", "url(reply_h.png)"); 
}); 
$(".reply").mouseout(function() { 
    $(this).css("background-image", "url(reply.png)"); 
}); 
+0

太好了。谢谢:) – Jon 2012-01-10 19:39:43

+0

我实际上使用mblase75的答案,因为他的职位是在你之前:( 对不起,希望我可以接受多个答案,但非常感谢你:) – Jon 2012-01-10 19:45:07