我想在我的代码中多次调用一个函数?

问题描述 投票:0回答:2

欢迎我计划每次单击按钮时都使此框移动但是问题是我第一次点击s或d却第一次无法正常工作这样任何人都可以帮助我找到解决问题的方法]

<!DOCTYPE html>
<html>

<head>
<style>
 .box {
    position: absolute;
    left: 10px;
    top: 20px;
    width: 20px;
    height: 20px;
    background-color: black;
    border: 1px solid black;
    border-radius: 5px;
}
              </style>
</head>

<body id="bd">

<div class="box"></div>

<script >

document.getElementById('bd').addEventListener('keypress', show);
function show(e){
    let x = e.which;
    if(x == 122){
       // 122 = z
    document.getElementsByClassName('box')[0].style.top -='50px' ;      
     }
     else  if(x == 133){
         // 122 = q
     document.getElementsByClassName('box')[0].style.left -='50px' ; 

    }
     else  if(x == 115){
       // 122 = s
     document.getElementsByClassName('box')[0].style.top +='50px' ; 
    }
     else  if(x == 100){
        // // 122 = d
     document.getElementsByClassName('box')[0].style.left +='50px' ;    
    }
}
</script>
</body>

</html>
javascript keypress design
2个回答
0
投票

[element.style.topelement.style.left是字符串,所以您的陈述实质上是在说]


0
投票

您正在尝试对字符串执行操作。首先需要转换数字。

© www.soinside.com 2019 - 2024. All rights reserved.