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

求助:按下左键时调用移动div盒子的函数的实现方法

问题分析与修正方案

你的代码已经尝试通过键盘事件调用myFunction,但存在语法错误、逻辑漏洞导致功能失效,以下是完整的修正实现:

修正后的完整代码

// 先获取要移动的div元素,替换为你实际的元素选择器
const object = document.getElementById('target-div');

window.addEventListener("keydown", function(e) {
  // 注意keyCode的大小写,JS是大小写敏感语言
  if (e.keyCode === 37 || e.keyCode === 39) {
    myFunction(e.key);
  }
});

function myFunction(s) {
  if (s === "ArrowLeft") {
    // 用getComputedStyle获取元素实际样式,避免初始无行内left属性的问题
    const computedStyle = window.getComputedStyle(object);
    let currentLeft = parseFloat(computedStyle.left);
    object.style.left = (currentLeft - 10) + "px";
  } else if (s === "ArrowRight") {
    // 补充右键移动逻辑(按需保留)
    const computedStyle = window.getComputedStyle(object);
    let currentLeft = parseFloat(computedStyle.left);
    object.style.left = (currentLeft + 10) + "px";
  }
}

关键修正细节

  • 修复e.keycode→e.keyCode、Replace→replace的大小写错误
  • 闭合了键盘事件的回调函数(原代码未结束回调逻辑)
  • 新增DOM元素获取代码,确保object变量指向目标div
  • 改用getComputedStyle获取实际left值,解决初始行内样式为空的问题
  • 补充右箭头移动逻辑(可根据需求删除)

调用说明

你无需手动调用myFunction,当按下左箭头(ArrowLeft)或右箭头(ArrowRight)时,键盘事件监听器会自动触发并调用该函数,传入对应的按键标识。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:51:24