Search

10/20/2007

javascript idiom: getComputedStyle + currentStyle

The first argument to this method is the element whose computed style is desired. The second argument is any CSS pseudoelement, such as ":before" or ":after" whose style is desired. You probably won't be interested in a pseudoelement, but in the Mozilla and Firefox implementation of this method, the second argument is required and may not be omitted.

var p = document.getElementsByTagName("p")[0]; // Get first paragraph of doc
var typeface = ""; // We want its typeface
if (p.currentStyle) // Try simple IE API first
typeface = p.currentStyle.fontFamily;
else if (window.getComputedStyle) // Otherwise use W3C API
typeface = window.getComputedStyle(p, null).fontFamily;

Computed styles are quirky, and querying them does not always provide the information you want. Consider the typeface example just shown. The CSS font-family attribute accepts a comma-separated list of desired font families for cross-platform portability. When you query the fontFamily attribute of a computed style, you're simply getting the value of the most specific font-family style that applies to the element. This may return a value such as "arial,helvetica,sans-serif", which does not tell you which typeface is actually in use. Similarly, if an element is not absolutely positioned, attempting to query its position and size through the top and left properties of its computed style often returns the value "auto". This is a perfectly legal CSS value, but it is probably not what you were looking for.

update:
  1. YUI的 YAHOO.util.Dom.getStyle(el, 'fontFamily') 的傳回值仍然是整組的css property.( ex: arial, verdana, sans-serif);
  2. 以下的例子是使用抓取 pseudoelement 'hover' 的方法
    console.log( window.getComputedStyle($('link'), 'hover').color );
    <a id="link" href="#">l;www.foo.bar</a>
    傳回值: rgb(0, 0, 238),明顯是錯誤的答案。(rgb(0, 0, 238)是FF預設的a:link color)
    Re: How is the hover pseudo-class translated into the DOM? from Bjoern Hoehrmann on 2007-03-26 (www-dom@w3.org from January to March 2007)
    Ok, here's the tricky part, according to this article, the only way to get the hover color is to fire getComputedColor() while hovering it. You can't set the second parameter to hover 'cause it's not a psudo-element, it's only a matching condition. Here's the example
    window.onload = function(){
    $('link').onmouseover = function(){
    console.log( window.getComputedStyle($('link'), null).color );
    }
    }
    the return value will be rgb(255, 0, 0) which is correct.

沒有留言: