set style with :hover javascript

前端 未结 2 1162
失恋的感觉
失恋的感觉 2021-02-06 01:55

I understand that the following method is great for setting CSS styles because of browser compatibility.

element.style.cssText = \"color:red;\";
<
2条回答
  •  [愿得一人]
    2021-02-06 02:23

    You could always add an individual style rule to an existing style sheet, instead of creating a new style element. Something along the lines of:

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

    I adapted the example at MDN
    This assumes you are using a class (that is already defined and applied) to add the :hover pseudo-selector to, but it could just as easily be an ID or element selector.

    If you were unable to add a class or style rule beforehand, you could also do that dynamically in much the same way (define class, define class:hover, then apply class to desired elements).

提交回复
热议问题