简体   繁体   English

Javascript document.defaultView或document.styleSheets?

[英]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. 我是JS的新手,我今天才读到有关document.styleSheets And my question is: 我的问题是:

  1. When we want to get just one style property (example: color), which should I use? 当我们只想获取一个样式属性(例如:color)时,应该使用哪个?
  2. What is document.styleSheets for? document.styleSheets是做什么用的? 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. document.styleSheets是加载到页面中的一个或多个实际样式表的列表。 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 . 如果您关心当前的计算样式是什么,则getComputedStyle().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. 现在,对于设置,如果您想将样式规则直接应用于单个元素, .style使用.style ,但是如果您想创建一个适用于许多(以及将来!)元素的新规则,则d要创建动态样式表/规则,并将其附加到.styleSheets集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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