【发布时间】:2021-11-26 18:27:44
【问题描述】:
我正在尝试使用箭头在正文中移动按钮。 放数字文字是错误的,我测试了它链接到HTML的代码。
document.body.addEventListener("keydown", function (evt) {
const btn = document.querySelector('button');
switch(evt.code) {
case 'ArrowUp':
btn.style.marginBottom =+ 10;
break;
case 'ArrowDown':
btn.style.marginTop =+ 10;
break;
case 'ArrowRight':
btn.style.marginLeft += 10;
break;
case 'ArrowLeft':
btn.style.marginRight =+ 10;
break;
default:
}
})
【问题讨论】:
-
IMO 将 DOM 作为状态存储是错误的(当您尝试
+=来自 DOM 的值时,实际上就是这种情况)。为什么不在代码中引入变量来跟踪预期的边距值,然后将它们写入 DOM?
标签: javascript dom switch-statement