Dav*_*ing 21 javascript css jquery stylesheet
是否可以在文档中获取CSS文件的整个文本内容?F.ex:
<link rel="stylesheet" id="css" href="/path/to/file.css">
<script>
var cssFile = document.getElementById('css');
// get text contents of cssFile
</script>
Run Code Online (Sandbox Code Playgroud)
我不是真的通过document.styleSheets获取所有CSS规则,还有另外一种方法吗?
更新:当然有ajax选项,我很欣赏给出的答案.但似乎没有必要使用已经在浏览器中加载的ajax重新加载文件.因此,如果有人知道另一种方法来提取当前CSS文件的文本内容(而不是CSS规则),请发布!
T.J*_*der 24
使用该特定示例(CSS与页面位于同一域中),您可以通过ajax
以下方式将文件作为文本读取:
$.ajax({
url: "/path/to/file.css",
dataType: "text",
success: function(cssText) {
// cssText will be a string containing the text of the file
}
});
Run Code Online (Sandbox Code Playgroud)
如果要以更结构化的方式访问信息,document.styleSheets
则是与文档关联的样式表数组.每个样式表都有一个名为cssRules
(或仅rules
在某些浏览器上)的属性,该属性是样式表中每个规则的文本数组.每条规则都有一个cssText
属性.所以你可以遍历那些,例如:
$.each(document.styleSheets, function(sheetIndex, sheet) {
console.log("Looking at styleSheet[" + sheetIndex + "]:");
$.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
console.log("rule[" + ruleIndex + "]: " + rule.cssText);
});
});
Run Code Online (Sandbox Code Playgroud)
实例 - 该示例有一个样式表,包含两个规则.
fca*_*ran 19
get
如果样式表包含在同一个域中,则可以使用简单的ajax 调用加载内容
更新后编辑:
我尝试使用此代码(在FX10上)作为概念证明,只使用一个CSS请求,但对我来说似乎有点hacky,应该进行测试和验证.如果javascript不可用,它也应该通过一些后备来改进.
CSS(外部文件test.css)
div { border: 3px solid red;}
Run Code Online (Sandbox Code Playgroud)
HTML/jQuery的
<!doctype html >
<html>
<head>
<!-- provide a fallback if js not available -->
<noscript>
<link rel="stylesheet" href="test.css" />
</noscript>
</head>
<body>
<div></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script>
$(document).ready(function() {
$.when($.get("test.css"))
.done(function(response) {
$('<style />').text(response).appendTo($('head'));
$('div').html(response);
});
})
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您应该在div中看到带有红色边框的CSS代码:)
享受.
在不使用 ajax 的情况下获得样式表的最接近方法是确实迭代所有 CSS 规则并将它们连接成一个字符串。这将生成删除所有注释和多余空格的原始文件。这是有道理的,因为浏览器只需要将解析后的样式表保存在内存中,而不是原始文件。它只有3行代码:
function css_text(x) { return x.cssText; }
var file = document.getElementById('css');
var content = Array.prototype.map.call(file.sheet.cssRules, css_text).join('\n');
Run Code Online (Sandbox Code Playgroud)