如何使用拨片键在JavaScript中移动图像?
我正在尝试构建一个简单的游戏,玩家可以在多个关卡之间移动 在我的例子中,播放器是一个图像。我试图使用javascript移动它,但它没有移动!我尝试过多个网站的建议,但都没有奏效如何使用拨片键在JavaScript中移动图像?,javascript,Javascript,我正在尝试构建一个简单的游戏,玩家可以在多个关卡之间移动 在我的例子中,播放器是一个图像。我试图使用javascript移动它,但它没有移动!我尝试过多个网站的建议,但都没有奏效 var avatar=document.getElementByClassName(“外星人化身”); var avatarStyle=document.getComputedStyle(“外星人化身”); var topValue=avatarStyle.getPropertyValue(“top”).replac
var avatar=document.getElementByClassName(“外星人化身”);
var avatarStyle=document.getComputedStyle(“外星人化身”);
var topValue=avatarStyle.getPropertyValue(“top”).replace(“px”,即“);
函数向下移动(元素){
var eStyle=window.getComputedStyle(元素);
var topValue=eStyle.getPropertyValue(“top”).replace(“px”,即“);
element.style.top=(数字(topValue)+20)+“px”;
}
向下移动(“元素”);
//从顶部样式属性中减去以向上移动
函数向上移动(元素){
var elStyle=window.getComputedStyle(元素);
var topValue=elStyle.getPropertyValue(“top”).replace(“px”,即“);
element.style.top=(数字(topValue)-20)+“px”;
}
//添加到“左侧样式”属性以向右移动
函数moveRight(元素){
var elStyle=window.getComputedStyle(元素);
var leftValue=elStyle.getPropertyValue(“左”).replace(“px”,即“);
element.style.left=(数字(leftValue)+20)+“px”;
}
//从“左样式”属性中减去以向左移动
函数左移(元素){
var elStyle=window.getComputedStyle(元素);
var leftValue=elStyle.getPropertyValue(“左”).replace(“px”,即“);
element.style.left=(数字(leftValue)-20)+“px”;
}
昵称
投诉的特派团总数
伟大的
美好的
坚持下去
美好的
开始
您正在使用getComputedStyle
来记住元素的位置,但我建议您在代码中跟踪元素的位置,而不仅仅是在HTML/CSS中。举个简单的例子:
let avatar = document.getElementById("alien-avatar");
let avatarx = 20;
let avatary = 20;
function movePlayerUp() {
avatary--;
avatar.style.top = avatary + "px";
}
更新
您还可以使用getBoundingClientRect
检查元素在DOM中的位置
function moveRight() {
let position = avatar.getBoundingClientRect();
let newposition = position.x + 10;
avatar.style.left = newposition + "px";
}
player元素需要一个id
<div id="alien-avatar"...></div>
javascript中没有什么比得上getElementByClass
。我想你是想用这个getElementsByClassName
。这是完整的javascript代码吗,因为里面没有名字alien
,你还是在用它。是的,我是完整的js文件,我用的是“alien avatar”在开头,这意味着什么呢?alien-avatar
也没有名为alien
的变量,所以您如何使用它代码>两次(+不存在的方法),这个引用错误:document.getComputedStyle(alien-avatar)
谢谢分享这个例子,但是请注意,我可以在我的js中使用Id而不是ClassName吗?您可以使用Id
只获取一个元素(播放器)GetElementsByCassName
将为您提供一个具有该类名的所有元素的数组。很抱歉问了太多问题,但我们不需要这样调用函数moveRight()?还是有别的办法?我不知道你的意思?我给出了两个建议,一个是通过跟踪变量中的位置,另一个是使用getBoundingClientRect请求当前位置。