您總是可以將單獨的樣式規則添加到現有的樣式表中,而不是創建新的樣式元素。沿着線的東西:
function addStyle() {
var style = document.styleSheets[0]; //select style sheet (0==first)
var styleSel = ".class:hover"; //define selector
var styleDec = "color: red;"; //define declaration
if(style.insertRule) { //for modern, DOM-compliant browsers
style.insertRule(styleSel+'{'+styleDec+'}', style.cssRules.length);
//I chose to do it this way to more easily support the addRule method, but
//know that insertRule only needs two parameters, full style rule
//(selector+prop/value declarations), and index to insert rule at
// styleSheets[0].insertRule(rule, index);
}else { //for IE < 9
style.addRule(styleSel, styleDec, -1);
}
}
我適應了example at MDN
這裏假設你使用的是類(已定義和應用)中加入:僞選擇懸停,但它很容易能是一個ID或元素選擇器。
如果您無法事先添加類或樣式規則,您也可以以相同的方式動態執行此操作(定義類,定義類:懸停,然後將類應用於所需元素)。
'onmouseover'與'hover'相同;您可以附加該事件並簡單地添加一個類,並通過該類的CSS樣式。具有較高的可重用性。 – Zirak 2011-05-15 05:56:36
爲什麼不在正常的css中定義它,只改變javascript中的類? – Dmitry 2011-05-15 06:01:19
@Zirak,差不多。 ':hover'只能在IE6的''標籤中使用,但'onmouseover'幾乎適用於所有的元素。他們是相似的,但不一樣。 – Blender 2011-05-15 06:03:06