You need to enable JavaScript to run this app. JS按星期修改页面样式及日期格式化问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

JS按星期修改页面样式及日期格式化问题咨询

解决方案

1. 日期格式调整

你当前生成的日期格式为「August 15-2021」是因为toLocaleString默认输出的结构为月份 日期, 年份(例如August 15, 2021),你只替换了, 为-,没有处理月份和日期之间的空格。
只需要修改替换逻辑,先移除逗号,再把所有空格替换为短横线即可:

var dayMonthYear = date.toLocaleString('en-US', {month:'long',day:'numeric',year:'numeric'})
  .replace(',', '') // 先移除年份前的逗号
  .replaceAll(' ', '-'); // 把所有空格替换为短横线

输出结果就会变成August-15-2021的格式。

2. 按星期动态修改页面样式

你原有判断代码存在两处核心错误:

  • 条件判断误用了赋值运算符=,应该使用严格相等运算符===做值比较
  • 不能直接在JS代码块里写CSS属性,需要操作document.body.style对象修改页面样式,且JS中的样式属性使用驼峰命名(比如backgroundColor而非background-color)

完整的判断逻辑如下,你可以自行调整各场景对应的色值:

if (weekday === 'Sunday') {
  // 周日样式
  document.body.style.backgroundColor = 'aqua';
  document.body.style.color = 'blue';
} else if (weekday === 'Saturday') {
  // 周六样式
  document.body.style.backgroundColor = 'lightgreen';
  document.body.style.color = 'darkgreen';
} else {
  // 工作日样式
  document.body.style.backgroundColor = 'white';
  document.body.style.color = 'black';
}

完整可运行代码

var date = new Date();
// 生成目标格式日期
var dayMonthYear = date.toLocaleString('en-US', {month:'long',day:'numeric',year:'numeric'})
  .replace(',', '')
  .replaceAll(' ', '-');
var weekday = date.toLocaleString('en-US', { weekday: 'long' })
// 输出日期
document.write(dayMonthYear + ' [' + weekday + ']');
// 按星期修改样式
if (weekday === 'Sunday') {
  document.body.style.backgroundColor = 'aqua';
  document.body.style.color = 'blue';
} else if (weekday === 'Saturday') {
  document.body.style.backgroundColor = 'lightgreen';
  document.body.style.color = 'darkgreen';
} else {
  document.body.style.backgroundColor = 'white';
  document.body.style.color = 'black';
}

内容的提问来源于stack exchange,提问作者RMaxwell87

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 23:51:01