Monday, March 28, 2011

Find non-active CSS properties

Is it possible to determine styles in a CSS file through Javascript?

I am trying to detect CSS properties that will be applied to an element in a certain state, :hover in this case, but without those properties currently being active on the element. I had thought about cloning the element, appending the clone as a sibling with display:none and querying properties that way, but I don't know how to force the :hover style through Javascript. Any ideas?

From stackoverflow
  • the hover style is applied by the browser, dependnt on the mouse movement. I don't think you can force it through JS. But why would you want to? just define another css class and assign it through the className property in JS.

    Martijn Laarman : alternatively: a:hover, .myAnchorHoverClass { /* my css */ } then just apply myAnchorHoverClass through Javascript
    roryf : Thanks Martijn, thats a good suggestion. I want to keep the :hover for non-JS degradation, and for some WebKit transitions.
  • To determine styles throught JS, you can do using className like this e.g:

    item.onmouseover = gohover;

    item.onmouseout = nohover;

    function gohover(){this.className = gClass;}

    ...

  • If I'm understanding your question correctly, it seems like what you're looking for is an XPath for CSS (pseudo-)classes. Other than fetching the CSS file with Ajax and searching with regex, I'm not aware of any method of retrieving style information from a CSS file.

    Christopher Parker : Wow. It seems as though I was wrong! I think [Jason Karns's answer](http://stackoverflow.com/questions/391757/find-non-active-css-properties/517495#517495) would be the closest you're going to get. See QuirksMode's [Change style sheet](http://www.quirksmode.org/dom/changess.html) page for even more information. ... I love learning new things!
  • I believe you are interested in the styleSheets array that is a property of the document (document.styleSheets) This array indexes all of the style sheets referenced by the current page and allows you to iterate over all of the style rules in each sheet. The W3C array (Firefox, Opera, Safari) for accessing css rules is cssRules whereas Microsoft's array is rules. The following code snippet is taken from www.quirksmode.org:

    var theRules = new Array();
    if (document.styleSheets[1].cssRules)
        theRules = document.styleSheets[1].cssRules
    else if (document.styleSheets[1].rules)
        theRules = document.styleSheets[1].rules
    

    Now theRules contains the rules for the second stylesheet for the document. See quirksmode's reference and compatibility tables for more info on accessing CSS rules from JavaScript.

0 comments:

Post a Comment