[英]set style with :hover javascript
據我所知,由於瀏覽器兼容性,以下方法非常適合設置CSS樣式。
element.style.cssText = "color:red;";
我不能做的是使用cssText
在:hover
和:focus
CSS事件上應用樣式。
我該怎么做而不是這個?
element.style.cssText = ":focus{color:red;}";
PS不要提及使用諸如onmouseover
之類的javascript事件而不是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或元素選擇器。
如果您無法事先添加類或樣式規則,您也可以以相同的方式動態地執行此操作(定義類,定義類:懸停,然后將類應用於所需元素)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.