【发布时间】:2022-08-16 22:08:12
【问题描述】:
我在 HTML 中迈出了第一步,我希望我的代码执行以下操作:
- 当按下右箭头键时,将圆圈移动到右侧
- 当按下向下箭头键时,将圆圈移动到底部
但相反,它执行以下操作: 当按下这些键中的一个时,他只移动一次并且不再移动。为什么是这样?
<html> <head> <title>HTML Test</title> <style> #circle { width: 50px; height: 50px; border-radius: 25px; background: red; position: absolute; } </style> </head> <body> <div id=\"circle\"></div> </body> <script> document.onkeydown = function (event) { var circle = document.getElementById(\"circle\"); if (event.keyCode == 39) { circle.style.left += 100; console.log(\"right\") } else if (event.keyCode == 40) { circle.style.top += 100; console.log(\"bottom\") } } </script> </html>
-
您需要将
...style.left和....style.top转换为不带单位的浮点数/数字,添加您希望它移动的值,再次将其转换回px并将该值分配给.style.基本上,那些样式属性是需要首先转换为数值的字符串....拖累,我知道... -
哦,这听起来很糟糕,但我们开始吧
-
另外,我刚刚意识到,您需要使用
window.getComputedStyle(...)来获取这些属性的当前实际值。.style.仅包含 CSS 中定义的值... -
似乎元素不是为我想在这里做的事情而制作的。我应该用帆布。
标签: javascript html css