2013-08-27 21 views
2

我有一個問題,當元素共享相同的類應用懸停與jQuery。這在僅使用CSS時工作得很好,但只要JQuery出現,它就會改變一切。問題當元素共享相同的類應用懸停與jQuery

CSS

.btn { 
background:#ccc; 
padding:10px; 
} 
.btn:hover { 
background:red; 
padding:10px; 
} 

HTML

<a class="btn">Button 1</a><br /><br /><br /> 
<a class="btn">Button 2</a><br /><br /><br /> 
<a class="btn">Button 3</a><br /><br /><br /> 

<div id="paragraph"><p>Everything works fine with normal css Hover...</p></div> 

<input type="button" id="btnchange" value="Change to JQuery Hover, blue color" /> 

JQuery的

$('#btnchange').bind('click', function() { 

       $(".btn").hover(function(){ 
       $(".btn").css({background: "blue"}); 
       },function(){ 
       $(".btn").css({background: "#ccc"}); 
       }); 

       $("#paragraph").html('<p>But then, when applying jquery hover, things work unexpectedly</p>'); 

}); 

這裏是現場Fiddle

我沒有修改HTML代碼,只需JQuery的。

回答

7

Revised jsFiddle

jQuery的代碼,因爲你寫的,選擇的類「BTN」的所有元素,並把它們全藍。您只需選擇觸發懸停事件的元素,然後將該元素變爲藍色。因此,

更改此:

$('.btn').css({background: "blue"}); 

這樣:

$(this).css({background: "blue"}); 
2

使用$(this)選擇懸停功能的內部目標的實際懸停的元素:

$(".btn").hover(function(){ 
    $(this).css({background: "blue"}); 
},function(){ 
    $(this).css({background: "#ccc"}); 
}); 
2

變化".btn"內部懸停到$(this)

JQuery Demo

$('#btnchange').bind('click', function() { 

        $(".btn").hover(function(){ 
        $(this).css({background: "blue"}); 
        },function(){ 
        $(this).css({background: "#ccc"}); 
        }); 

        $("#paragraph").html('<p>But then, when applying jquery hover, things work unexpectedly</p>'); 

});