2011-05-15 30 views
5

據我所知,下面的方法是偉大的設置CSS樣式,因爲瀏覽器的兼容性。設置風格與:懸停javascript

element.style.cssText = "color:red;"; 

我不能做的是使用cssText:hover:focus CSS事件應用樣式。
我該做什麼而不是這個?

element.style.cssText = ":focus{color:red;}"; 

P.S. (它不適合我的情況)別提使用JavaScript事件,如onmouseover而不是CSS :hover

+0

'onmouseover'與'hover'相同;您可以附加該事件並簡單地添加一個類,並通過該類的CSS樣式。具有較高的可重用性。 – Zirak 2011-05-15 05:56:36

+0

爲什麼不在正常的css中定義它,只改變javascript中的類? – Dmitry 2011-05-15 06:01:19

回答

7

你可以用各種巧妙的做到這一點:

var head = document.getElementsByTagName('head')[0]; 
var style = document.createElement('style'); 
var declarations = document.createTextNode('selector:pseudo { property: value }'); 

style.type = 'text/css'; 

if (style.styleSheet) { 
    style.styleSheet.cssText = declarations.nodeValue; 
} else { 
    style.appendChild(declarations); 
} 

head.appendChild(style); 

你需要的不正是,但是如果你願意的話,你可以調整它並做出一個奇特的功能。

+0

什麼是「巫毒魔法」?請解釋。我當然不喜歡這些內涵。 – 2011-05-16 04:05:25

+8

「巫毒術魔法」 - >非直覺的解決方案。 – Blender 2011-05-16 05:13:00

0

您總是可以將單獨的樣式規則添加到現有的樣式表中,而不是創建新的樣式元素。沿着線的東西:

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或元素選擇器。

如果您無法事先添加類或樣式規則,您也可以以相同的方式動態執行此操作(定義類,定義類:懸停,然後將類應用於所需元素)。