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

JavaScript色相反转器无法正常运行,如何排查修复?

色相反转器代码问题分析与修复

代码中的核心问题:

  • DOM操作错误:你当前是读取hue-o的文本内容赋值给outputHue变量,然后修改这个变量——这不会同步到页面上。必须直接操作DOM元素的textContent属性才能更新显示。
  • 合法值判断遗漏0:色相值0是有效范围,但你的条件inputHue > 0会把0判定为非法,触发错误提示。
  • 非数字输入处理缺失:如果输入非数字,Number()转换后得到NaN,此时会直接走非法范围提示,不够直观。

修正后的代码:

JavaScript代码:

function invertHue() {
  const inputElement = document.getElementById("hue-i");
  const inputHue = Number(inputElement.value);
  const outputElement = document.getElementById("hue-o");
  let result;

  // 先校验是否为有效数字
  if (isNaN(inputHue)) {
    window.alert("请输入有效的数字");
    inputElement.value = "";
    return;
  }

  if (inputHue >= 0 && inputHue <= 180) {
    result = inputHue + 180;
    outputElement.textContent = result;
  } else if (inputHue > 180 && inputHue <= 360) {
    result = inputHue - 180;
    outputElement.textContent = result;
  } else {
    window.alert("色相值必须在0到360之间");
    inputElement.value = "";
  }
}

HTML代码(无需修改):

<div class="input">
  <input type="text" id="hue-i" placeholder="Enter hue here...">
  <button id="invert-btn" onclick="invertHue()">Invert</button>
</div>
<div class="output">
  <p id="hue-o">Inverted hue will appear here...</p>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:53:11