Why doesn't getComputedStyle work with pseudo classes like :hover?

后端 未结 2 863
慢半拍i
慢半拍i 2020-12-06 10:45

The function window.getComputedStyle is supposed to be able to get the computed style of pseudo classes like :hover, according to the documentation.

It\

2条回答
  •  一向
    一向 (楼主)
    2020-12-06 11:42

    var style = window.getComputedStyle(element[, pseudoElt]);
    

    where pseudoElt is "a string specifying the pseudo-element to match". A pseudo-element is something like ::before or ::after, those are elements which are generated by CSS styles. :hover, :visited or other similar effects are pseuodo-classes. They won't create new elements but apply specialized class styles to the element.

    It's not possible to get the computed style of a pseudo-class, at least not with getComputedStyle. You can however traverse through the CSS rules and try to find a fitting selector, but I won't recommend you to do this, since some browsers won't follow the DOM-Level-2-Style rules and you would have to check which rule will affect your specific element:

    /* Style */
    p a:hover{ color:yellow; background:black;}
    p > a:hover{ color:green; background:white;}
    p > a+a:hover{ color:fuchsia; background:blue;}
    
    // JS
    var i,j, sel = /a:hover/;
    for(i = 0; i < document.styleSheets.length; ++i){
        for(j = 0; j < document.styleSheets[i].cssRules.length; ++j){    
            if(sel.test(document.styleSheets[i].cssRules[j].selectorText)){
                console.log(
                    document.styleSheets[i].cssRules[j].selectorText,
                    document.styleSheets[i].cssRules[j].style.cssText
                );
            }
        }
    }
    
    Result:
    p a:hover color: yellow; background: none repeat scroll 0% 0% black; 
    p > a:hover color: green; background: none repeat scroll 0% 0% white;
    p > a + a:hover color: fuchsia; background: none repeat scroll 0% 0% blue;

    See also:

    • MDN: getComputedStyle examples
    • W3C: CSS2: 5.10 Pseudo-elements and pseudo-classes
    • SO: Setting CSS pseudo-class rules from JavaScript

提交回复
热议问题