[英]How can i read CSS rule from local file with JavaScript
我想做的是读取css文件(本地文件)中的内容,但是
我的目标是保存一个html文件,但在此之前要从链接样式表获取css并将其添加到之间的html文件中
css=' <style>\n'
//+ get the css
+ '</style>\n';
您的问题的解决方案是:
<style>
@import url("style.css");
</style>
链接样式表的经典方法。
jQuery的方式:
<!doctype html >
<html>
<head>
<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>
使用必须将所有路径作为相对路径,而不是绝对路径。 您的结构应如下所示:
root
| - index.html
| - css
| -- styles.css
| -- images
| --- background.png
| --- button.jpg
| - js
| -- main.js
然后在index.html中使用相对路径:
<html>
<link href="/css/styles.css"></style>
<script src="/js/main.css">
当使用file://
协议时,CORS规则严格适用于浏览器:所有请求的资源必须与当前文件处于同一级别或更低级别(在dir树中更深)。
因此,由于CORS,如果您在root/pages/index.html
有文件,则它无法请求../css/styles.css
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.