我试图在main.js文件夹中提取不同的样式表,具体取决于一天中的时间。但是,我一直在控制台中收到文件未找到错误。
当我打开检查元素时。 day.css文件出现在DOM中,但在控制台中我收到文件未找到错误且文件路径不正确。
浏览器将路径显示为: 文件:///Users/myname/Documents/directory/foodclock/day.css
但应该是: 文件:///Users/myname/Documents/directory/foodclock/css/day.css
---这是我的Javascript代码----
function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
}
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='evening.css' type='text/css'>");
}
if (22 <= currentTime&¤tTime <= 24) {
document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
}
}
getStylesheet();
有关解决此问题的任何建议吗? 提前谢谢!
答案 0 :(得分:0)
在每个“href”元素中添加“css /”。像这样:
function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='css/morning.css' type='text/css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='css/day.css' type='text/css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='css/evening.css' type='text/css'>");
}
if (22 <= currentTime&¤tTime <= 24) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
}
getStylesheet();
答案 1 :(得分:0)
您需要在所有href链接前指定css /,因为css样式表存在于不同的目录css
function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='css/morning.css' type='text/css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='css/day.css' type='text/css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='css/evening.css' type='text/css'>");
}
if (22 <= currentTime&¤tTime <= 24) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
}
getStylesheet();