如何使用JavaScript通过方向键修改div实例的left位置
问题根源
square2.div.style.left的返回值是带px单位的字符串,初始状态下这个值为"50px"。你用+=做运算时本质是执行字符串拼接,最终会得到"50px100px"这类不符合CSS规范的无效值,浏览器会直接丢弃无效样式,所以元素不会产生位移。
修复方法
不要直接对带单位的样式字符串做加法,你在Square类里已经定义了xPos存储数值类型的x轴坐标,直接维护这个数值变量,更新后重新赋值给样式即可。顺手把测试用的alert删掉,避免每次按键弹框打断交互,还可以把移动逻辑封装成类方法,四个方向的移动都能复用。
class Square { constructor(length) { this.width = length; this.height = length; this.div = document.createElement("div"); this.div.style.position = "absolute"; this.div.style.backgroundColor = "red"; this.div.style.width = length + "px"; this.div.style.height = length + "px"; document.body.appendChild(this.div); // 用类属性存储数值类型的坐标,避免反复解析带单位的样式字符串 this.xPos = 50; this.yPos = 0; this.div.style.left = this.xPos + "px"; this.div.style.top = this.yPos + "px"; } move(xOffset, yOffset) { this.xPos += xOffset; this.yPos += yOffset; this.div.style.left = this.xPos + "px"; this.div.style.top = this.yPos + "px"; } } const square2 = new Square(10); window.addEventListener( "keydown", function (event) { if (event.defaultPrevented) return; switch (event.key) { case "ArrowDown": square2.move(0, 100); break; case "ArrowUp": square2.move(0, -100); break; case "ArrowLeft": square2.move(-100, 0); break; case "ArrowRight": square2.move(100, 0); break; default: return; } event.preventDefault(); }, true );
补充提示
- 如果你非要直接操作style属性值,需要先把字符串里的数值解析出来,比如
const currentLeft = parseInt(square2.div.style.left, 10),计算完新值后再拼接px回写,但这种方式需要频繁做类型转换,维护成本比单独存数值坐标高很多。 - 测试前先点击页面空白处激活窗口焦点,否则页面捕获不到键盘事件,按键不会有反应。
内容的提问来源于stack exchange,提问作者AppCreator
相关产品推荐
相关产品推荐

