我试图通过了解如何使用 vanilla javascript 来了解与修改样式表相关的 jquery 是如何工作的,但是我找不到很多关于这个主题的资源。我已经检查了关于该主题的堆栈流页面,但我无法弄清楚我做错了什么。
我有一个简单的html页面和一个简单的样式表,html页面中的javascript在脚本标签中
html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="parent"></div>
<script>
let parent=document.getElementsByClassName('parent')[0];
for(let i=0; i<10;i++){
let child=document.createElement('div');
let id= "i"+ i.toString();
child.setAttribute("id",id);
parent.appendChild(child);
}
</script>
</body>
</html>
样式表
body{
background-color: lightblue;
}
.parent{
display:flex;
flex-wrap: wrap;
flex-direction: column;
}
.parent div{
margin: 5px;
width: 50px;
height: 50px;
background-color: white;
}
控制台命令
当我设置样式以拉出样式表对象时,在控制台中我得到了对象,也就是样式表,但 cssRules 属性设置为 null,其中没有样式表中的任何规则。我想不通这是为什么。
例如
document.styleSheets //returns StyleSheetList {0: CSSStyleSheet, length: 1}
document.styleSheets[0] /*returns CSSStyleSheet {ownerRule: null, cssRules:
null, rules: null, type: "text/css", href:
"file:///C:/Users/brand/Documents/test/main.css"…}*/
最佳答案
对样式表数据的访问受制于 the Same Origin Policy .大多数浏览器认为任何 file:///
URL 都来自不同的来源。
您需要使用 HTTP 或 HTTPS 来访问文档,并且样式表的来源相同。
关于javascript - 为什么我尝试使用 document.stylesheets 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515124/