You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

工作日规划器:根据当前时间动态设置文本区域颜色问题求助

工作日规划器文本区域颜色动态设置方案

问题诊断

现有代码存在多处核心错误:

  • HTML中所有textarea复用同一txtarea id,违反id唯一性规则,无法精准定位元素
  • JavaScript中直接拿行元素数组与时间变量比较,未提取行对应的时间数值
  • 获取文本框时误用getElementById("#textarea")(语法错误),且通过innerHTML获取的是文本内容而非DOM元素本身
  • 条件判断使用赋值符号=而非比较符号===,逻辑完全失效

修正后代码实现

优化后的HTML结构

移除重复id,通过类选择器定位文本区域:

<div id="9" class="row">
    <div class="col-2 col-md-1 hour text-center py-3">9AM</div>
    <textarea class="col-8 col-md-10 description" rows="3"></textarea>
    <button class="btn saveBtn col-2 col-md-1" aria-label="save">
        <i class="fas fa-save" aria-hidden="true"></i>
    </button>
</div>
<div id="10" class="row">
    <div class="col-2 col-md-1 hour text-center py-3">10AM</div>
    <textarea class="col-8 col-md-10 description" rows="3"></textarea>
    <button class="btn saveBtn col-2 col-md-1" aria-label="save">
        <i class="fas fa-save" aria-hidden="true"></i>
    </button>
</div>

修正后的JavaScript代码

假设currenttime为已获取的24小时制小时数(如9、10):

// 替换为你已获取的currenttime值,示例为获取当前系统小时
const currentTime = new Date().getHours();

function setTimeBlockColors() {
    const rowList = document.querySelectorAll(".row");
    
    rowList.forEach(row => {
        // 从行id提取对应小时数值
        const rowHour = parseInt(row.id);
        // 获取当前行的文本区域
        const textArea = row.querySelector(".description");
        
        // 按时间逻辑设置颜色
        if (currentTime === rowHour) {
            textArea.style.backgroundColor = "#ffd700"; // 当前时间:金色
        } else if (currentTime > rowHour) {
            textArea.style.backgroundColor = "#d3d3d3"; // 已过时间:灰色
        } else {
            textArea.style.backgroundColor = "#98fb98"; // 未到时间:浅绿色
        }
    });
}

// 初始化执行
setTimeBlockColors();
// 可选:每分钟自动更新,适配时间变化
setInterval(setTimeBlockColors, 60000);

核心逻辑说明

  1. 时间匹配:通过行元素的id(如"9")转换为数字,作为该行的时间标识
  2. 元素定位:利用row.querySelector(".description")精准获取当前行内的文本区域,规避id重复问题
  3. 样式控制:根据当前时间与行时间的对比结果,分别设置三种不同背景色(可替换为color属性修改文本颜色)
  4. 实时更新:添加定时器实现每分钟自动刷新,确保颜色随时间动态变化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:50:29