【发布时间】:2014-02-25 23:47:28
【问题描述】:
目录结构:
html/index.html
html/css/css.css
html/css/img/avatar.png
css.css 的内容:
body {
background-image: url("./img/avatar.png");
}
如果在 index.html 中使用“链接”标签包含 css.css 文件,它可以正常工作,并且 avatar.png 显示为页面背景:
<link rel="STYLESHEET" type="text/css" href="./css/css.css">
但是,如果使用 JavaScript 代码包含 css.css 文件,那么控制台会显示错误:
function load_css(){
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.readyState === 4)
if (xhr.status === 200) {
var oNew = document.createElement('style');
oNew.rel = 'STYLESHEET';
oNew.type = 'text/css';
oNew.textContent = xhr.responseText;
document.getElementsByTagName("head")[0].appendChild(oNew);
}
}
xhr.open("GET", './css/css.css', false);
xhr.send(null);
}
load_css();
控制台:
GET http://localhost/html/img/avatar.png 404 (Not Found)
它不适用于所有浏览器。
看起来,当使用上述方法以编程方式包含 CSS 文件时,该 CSS 内的相对链接相对于包含它们的 HTML 文件而不是包含它们的 CSS 文件变得相对。
有什么补救建议吗?
【问题讨论】:
-
使用 CSS 文档的绝对路径。
-
另外,我不知道您的设置中的
/html/是什么,但看起来您的文件夹少了一个。我的 XAMPP 设置是http://localhost/*site-folder*/yadayada
标签: javascript html css xmlhttprequest stylesheet