用javascript按日期加载css

Load css by date with javascript

本文关键字:加载 css 日期 javascript      更新时间:2023-09-26

我希望根据日期(季节)加载不同的css文件。

我试着从这里修改一个图像脚本的stackoverflow,但没有工作。

有谁能指出哪里出错了吗?
<link href="/css_season/default.css" rel="stylesheet" type="text/css" onload="logo(this)">
function logo(link) {
  var d = new Date();
  var Today = d.getDate();
  var Month = d.getMonth();
  var src;
  if (Month === 4 && (Today >= 1 && Today <= 30)) {
    src = "/css_season/easter.css";
  } else if (Month === 7 && (Today >= 1 && Today <= 31)) {
    src = "/css_season/vacation.css";
  } else if ((Month === 8 && Today >= 30) || (Month === 0 && Today <= 2)) {
    src = "/css_season/vacation.css";
  } else if (Month === 12 && (Today >= 15 && Today <= 31)) {
    src = "/css_season/holidays.css";
  } 
  link.href=href;
}

您的分配link.href=href不会工作,因为href没有定义。此外,我会将logo函数放在<body onload="logo();">中,并为link标记提供id属性。

这应该为您工作:

<html>
<head>
<link id="cssId" href="/css_season/default.css" rel="stylesheet" type="text/css"/>
</head>
<body onload="logo();">
 <!-- body content here -->
</body>
function logo() {
  var d = new Date();
  var Today = d.getDate();
  var Month = d.getMonth();
  var src;
  if (Month === 4 && (Today >= 1 && Today <= 30))
    src = "/css_season/easter.css"; 
  else if (Month === 7 && (Today >= 1 && Today <= 31))
    src = "/css_season/vacation.css";
  else if ((Month === 8 && Today >= 30) || (Month === 0 && Today <= 2))
    src = "/css_season/vacation.css";
  else if (Month === 12 && (Today >= 15 && Today <= 31))
    src = "/css_season/holidays.css";
  document.getElementById('cssId').href=src;
}

js函数末尾赋值错误。
link.href=href;应为link.href = src;

欢呼