[英]How can i read CSS rule from local file with JavaScript
what i want to do is to read what's inside a css file ( local file ) but 我想做的是读取css文件(本地文件)中的内容,但是
my goal is to save an html file but before that to get the css from link stylesheet and add it to the html file between 我的目标是保存一个html文件,但在此之前要从链接样式表获取css并将其添加到之间的html文件中
css=' <style>\n'
//+ get the css
+ '</style>\n';
The solution to your problem is: 您的问题的解决方案是:
<style>
@import url("style.css");
</style>
Classic way to link stylesheets. 链接样式表的经典方法。
JQuery way: 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>
Use must have all paths as relative ones instead of absolute. 使用必须将所有路径作为相对路径,而不是绝对路径。 And your structure should be like this:
您的结构应如下所示:
root
| - index.html
| - css
| -- styles.css
| -- images
| --- background.png
| --- button.jpg
| - js
| -- main.js
Then you use relative paths in index.html: 然后在index.html中使用相对路径:
<html>
<link href="/css/styles.css"></style>
<script src="/js/main.css">
CORS rules applies strictly in browser when on file://
protocol: all resources that are being requested must be on same level as current file or below (deeper in dir tree). 当使用
file://
协议时,CORS规则严格适用于浏览器:所有请求的资源必须与当前文件处于同一级别或更低级别(在dir树中更深)。
So if you have file in root/pages/index.html
it can't request ../css/styles.css
because of CORS. 因此,由于CORS,如果您在
root/pages/index.html
有文件,则它无法请求../css/styles.css
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.