2012-12-04 29 views
27

某些CSS樣式需要應用於懸停的元素,並且CSS樣式必須直接使用javascript/jquery應用,而不是通過樣式表或$(this).addClass('someStyle'),因爲我正在將DOM元素注入到另一頁。通過jQuery/Javascript添加懸停CSS屬性

我們可以通過

$('#some-content').css({ 
    marginTop: '60px', 
    display: 'inline-block' 
}); 

我們應該如何添加CSS樣式:hover事件採用通常的CSS樣式?


難道我們不得不訴諸:和

$('#some-content').hover(
     function(){ $(this).css('display', 'block') }, 
     function(){ $(this).css('display', 'none') } 
) 
+0

看的'.hover()中的jquery'方法。 http://api.jquery.com/hover/ –

+0

爲什麼不添加和刪除基於jquery或onmouseover和onmouseout中的懸停事件的類? –

+0

你想要元素消失時,你已經遠離它?你應該如何將鼠標懸停在它上面? – Alnitak

回答

21

我發現使用的mouseenter鼠標離開比懸停更好。有更多的控制。

$("#somecontent").mouseenter(function() { 
    $(this).css("background", "#F00").css("border-radius", "3px"); 
}).mouseleave(function() { 
    $(this).css("background", "00F").css("border-radius", "0px"); 
}); 
+5

小心詳細說明「有更多控制權」聲明?據我所知,'.hover()'函數只是簡單地完成你所編碼的內容。 –

+3

我只是喜歡它的明確說'鼠標進入元素'和'鼠標離開元素'。但是,此頁面上的圖表表明,在優化方面,實時鼠標滑鼠/鼠標滑鼠是最好的。 http://jsperf.com/hover-vs-mouseenter – Jon

12

試試這個:

$('#some-content').hover(function(){ 
    $(this).css({ marginTop: '60px', display: 'inline-block' }); 
}, function(){ 
    $(this).css({ //other stuff }); 
}); 

或使用類

$('#some-content').hover(function(){ 
    $(this).toggleClass('newClass'); 
}); 

更多的信息在這裏.hover().toggleClass()

3

你應該把它們放在一個hover事件:

var elem = $('#elem'); 

elem.hover(function() { 
    // ... :hover, set styles 
}, function() { 
    // ... this function is called when the mouse leaves the item, set back the 
    //  normal styles 
}); 

但是,我完全推薦把你的CSS放在類中,並在JS中使用這些類,你應該儘可能多地拆分語言。