简体   繁体   English

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

[英]i want to call a function many time inside my code?

I plan to make this box move every time I click a button but the problem is that it works first time when I click s or d but does not work after that.我打算每次单击按钮时都使此框移动,但问题是第一次单击sd时它可以工作,但之后就不起作用了。 So can any one help me to find the solution to my problem?那么任何人都可以帮助我找到解决问题的方法吗?

<!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>

element.style.top and element.style.left are strings, so your statements are essentially saying element.style.topelement.style.left是字符串,所以你的陈述本质上是在说

element.style.top = "20px" + "50px";

Instead, consider a separate variable storing position:相反,考虑一个单独的变量存储位置:

let positionLeft = 20;

...

if(x == 115){
    positionLeft += 50;
    document.getElementsByClassName('box')[0].style.top = positionLeft + 'px'; 
}

You are trying to perform operation on string.您正在尝试对字符串执行操作。 First need to convert in number.首先需要转换数字。

Sample:样本:

 <!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> const number = (num) => Number(num.split('px')[0]) const addBy50 = (num) => `${number(num) + 50}px` const subtractBy50 = (num) => `${number(num) - 50}px` const style = document.getElementsByClassName("box")[0].style document.addEventListener("keypress", (e) => { let x = e.which; const { top, left } = style switch (e.which) { case 122: style.top = subtractBy50(top); break; case 113: style.left = subtractBy50(left); break case 115: style.top = addBy50(top); break case 100: style.left = addBy50(left); break } }); </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM