我了解以下方法适用于设置 CSS 样式,因为它具有浏览器兼容性。
element.style.cssText = "color:red;";
我不能使用cssText
来应用样式到:hover
和:focus
CSS事件。
我该如何做才能实现这个效果?
element.style.cssText = ":focus{color:red;}";
附言:不要提到使用JavaScript事件,例如onmouseover
代替CSS的:hover
(这不适合我的情况)。
我了解以下方法适用于设置 CSS 样式,因为它具有浏览器兼容性。
element.style.cssText = "color:red;";
我不能使用cssText
来应用样式到:hover
和:focus
CSS事件。
我该如何做才能实现这个效果?
element.style.cssText = ":focus{color:red;}";
附言:不要提到使用JavaScript事件,例如onmouseover
代替CSS的:hover
(这不适合我的情况)。
你可以通过一些巫术魔法来实现:
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);
虽然不完全符合您的需求,但如果您愿意,可以对其进行微调并制作出一个漂亮的函数。
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伪选择器,但它也可以很容易地是ID或元素选择器。
如果您无法事先添加类或样式规则,则也可以以类似的方式动态执行此操作(定义类,定义class:hover,然后将类应用于所需元素)。
onmouseover
与hover
是相同的;您可以附加该事件并简单地添加一个类,然后通过CSS样式化该类。具有更高的可重用性。 - Zirak:hover
仅适用于<a>
标签,但onmouseover
适用于几乎所有元素。它们相似,但并不完全相同。 - Blender