最近排查一个很奇怪的线上问题,在本地以及测试环境样式都是正常的,而模拟和正式环境样式是有问题的,代码是一套;然后就从那套代码里找问题,最后发现是
document.styleSheets
搞的鬼
document.styleSheets
From MDN:The styleSheets
read-only property of the Document
interface returns a StyleSheetList
of CSSStyleSheet
objects, for stylesheets explicitly linked into or embedded in a document. 也就是,返回由网页中所用到的样式表组成的数组,但不包含行内样式。
我们可以利用document.styleSheets
,通过js方法去修改样式
在发布之后却发现控制台报错了~~~~~~~ 在对比了测试环境和正式环境的document.styleSheets
返回值后发现差异,正式环境和href
字段的值不是同一个域名,传说中的跨域啦。。。。
📢📢 度娘一番后得知:
In latest Chrome, CORS security rules are applicable for style-sheets also (Similar to Iframe rules).You can load and render them but, cannot access the content through javascript (If loaded from Cross-Domain ).If your CSS Stylesheet is from Same domain as of HTML /or included in same HTML file, you will be able to access
document.styleSheets[elem].cssRules
otherwise it will throw error
cssRules: [Exception: DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules at CSSStyleSheet.invokeGetter (<anonymous>:3:28)]
得知这个原因后,弱小的我们不可能去改资源配置,就采用了通过css去直接实现给功能。忘大家引以为戒,不被这个问题所困扰许久!!