设置样式:悬停javascript

Web*_*ner 8 javascript css dom stylesheet

据我所知,由于浏览器兼容性,以下方法非常适合设置CSS样式.

element.style.cssText = "color:red;";
Run Code Online (Sandbox Code Playgroud)

我不能做的是使用cssText对应用样式:hover:focusCSS事件.
我该怎么做而不是这个?

element.style.cssText = ":focus{color:red;}";
Run Code Online (Sandbox Code Playgroud)

PS不要提及使用javascript事件,onmouseover而不是CSS :hover(它不适合我的情况.)

Ble*_*der 9

你可以用一些巫毒魔法来做到这一点:

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);
Run Code Online (Sandbox Code Playgroud)

不完全是你所需要的,但如果你愿意的话,你可以调整它并制作一个奇特的功能.