2012-01-10 54 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