11

when get a element's style, we always use

if(document.defaultView && document.defaultView.getComputedStyle) to check whether the browser support the method or not.

why not use if(window.getComputedStyle)?

looping
  • 1,141
  • 3
  • 11
  • 20
  • See https://developer.mozilla.org/en/DOM/window.getComputedStyle for an explanation + exception (under `defaultView`) – Alex K. Nov 15 '11 at 12:53

2 Answers2

7

So in short, the reason why we use document.defaultView && document.defaultView.getComputedStyle is that we want a cross-browser working-on-every-element method of checking whenever it supports fetching computed styles.

Simple if(window.getComputedStyle) would fail for iframes in Firefox 3.6 (according to article linked in comment by Alex K.).

WTK
  • 16,583
  • 6
  • 35
  • 45
1

According to the MDN defaultView is no longer required

In many code samples, getComputedStyle is used from the document.defaultView object. In nearly all cases, this is needless, as getComputedStyle exists on the window object as well. It's likely the defaultView pattern was a combination of folks not wanting to write a testing spec for window and making an API that was also usable in Java.

There was a bug in Firefox 3.6 (2010/2011) that needed defaultView fix

Drenai
  • 11,315
  • 9
  • 48
  • 82