简体   繁体   中英

Javascript document.defaultView or document.styleSheets?

When we want a more reliable way to get the style of an element, we use

document.defaultView.getComputedStyle..

instead of

document.getElmById(x).style.color..

BUT, there is another, and it is

document.styleSheets...

I'm new to JS, I just read about document.styleSheets today. And my question is:

  1. When we want to get just one style property (example: color), which should I use?
  2. What is document.styleSheets for? When should it be used?
  3. When we want to add a method that looks like this:

     // it applies multiple properties elm.setStyle({ color: '#f00', marginLeft: x, opacity: 0.5, background: '#000 url(x.jpg) left top no-repeat' }); 

Which should I use to be the base of the function?

Finally, Thanks for all your help!

document.styleSheets is the list of the actual stylesheet or sheets loaded into the page. Fun fact: you can dynamically create new "stylesheets" and add them to this list, without actually loading separate files.

If you are looking up the current style of an element, the question you need to ask is, "do I care more what the stylesheet SAYS the style should be, or do I care more what the actual current (computed) style is?" The circumstances will determine which is more appropriate.

If you care about the original declared styles, you'll want to consult the stylesheets themselves. However, this is quite a bit more complex than it may seem, because you're going to have to parse the files and find all the cascading styles that would apply to the element in question.

If you care about what the current computed styles are, getComputedStyle() is more reliable that .style .

Now, for setting, if you want to apply a style rule directly to a single element, you'd want to use .style , but if you want to create a new rule that applies to many (and future!) elements, you'd want to create a dynamic stylesheet/rule and append it to the .styleSheets collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM