Set style with: hover javascript

I understand that the following method is great for customizing CSS styles due to browser compatibility.

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

What I cannot do is use cssTextto apply styles in events :hoverand :focusCSS.
What should I do instead?

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

PS Do not mention the use of javascript events such as onmouseover, not CSS :hover(this does not match my situation.)

+5
source share
2 answers

You can do this with some Voodoo magic:

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);

Not what you need, but you can customize it and make yourself an unusual function if you want.

+7

. - :

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);
    }
}

MDN
, ( ), -: hover, .

, ( , : , ).

0

All Articles