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

重复触发keydown事件时如何取消对应样式效果恢复元素默认状态

实现方向键切换元素背景色解决方案

我们只需要在每次触发按键事件时,判断目标元素当前是否为高亮背景,是则切回原始背景,否则切换为高亮背景即可,有两种常见实现方式:


方案1:基于原有style操作逻辑最小改动

核心思路是提前缓存元素的原始背景色,每次按键做状态判断,对原有代码侵入性最低:

document.addEventListener("keydown", pressKeyOn);
const arUp = document.querySelector(".ar-up");
const arLeft = document.querySelector(".ar-left");
const arRight = document.querySelector(".ar-right");
const arDown = document.querySelector(".ar-down");

// 缓存各元素初始原始背景色
const originalBg = {
  up: getComputedStyle(arUp).backgroundColor,
  down: getComputedStyle(arDown).backgroundColor,
  left: getComputedStyle(arLeft).backgroundColor,
  right: getComputedStyle(arRight).backgroundColor
}

function pressKeyOn(e) {
  // 提示:keyCode已被Web标准废弃,生产环境可替换为e.key判断
  switch(e.keyCode) {
    case 38: // 上键
      arUp.style.backgroundColor = getComputedStyle(arUp).backgroundColor === 'red' ? originalBg.up : 'red';
      break;
    case 40: // 下键
      arDown.style.backgroundColor = getComputedStyle(arDown).backgroundColor === 'green' ? originalBg.down : 'green';
      break;
    case 39: // 右键
      arRight.style.backgroundColor = getComputedStyle(arRight).backgroundColor === 'navy' ? originalBg.right : 'navy';
      break;
    case 37: // 左键
      arLeft.style.backgroundColor = getComputedStyle(arLeft).backgroundColor === 'violet' ? originalBg.left : 'violet';
      break;
  }
}

注意:这里用getComputedStyle获取元素实际渲染的背景色,避免原始背景写在CSS类中无法通过element.style.backgroundColor读取的问题。


方案2:更易维护的CSS类切换方案

把样式逻辑交给CSS处理,JS只负责切换类名,符合关注点分离原则,代码更简洁:
首先添加CSS样式:

/* 提前定义高亮类 */
.ar-up.active { background-color: red; }
.ar-down.active { background-color: green; }
.ar-left.active { background-color: violet; }
.ar-right.active { background-color: navy; }

修改JS代码:

document.addEventListener("keydown", pressKeyOn);
const arUp = document.querySelector(".ar-up");
const arLeft = document.querySelector(".ar-left");
const arRight = document.querySelector(".ar-right");
const arDown = document.querySelector(".ar-down");

function pressKeyOn(e) {
  switch(e.keyCode) {
    case 38:
      arUp.classList.toggle('active');
      break;
    case 40:
      arDown.classList.toggle('active');
      break;
    case 39:
      arRight.classList.toggle('active');
      break;
    case 37:
      arLeft.classList.toggle('active');
      break;
  }
}

classList.toggle方法会自动判断元素是否存在对应类,存在则移除,不存在则添加,刚好匹配按一次切换一次状态的需求,后续修改高亮样式只需要调整CSS即可,不用改动JS逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:15:08