发生什么:当我按空格键时,球向上移动并停止;当再次按下时,球向下移动。
我需要什么:当我按下空格键时,球应该先向上然后向下移动!
我想说一下如何一键重复两次此功能。按下空格键时,我尝试了两次循环,但效果不如预期。有什么建议么?
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
var x = 0;
var y = 0;
var counter = 0;
var inc = Math.PI / 100 ;
body.addEventListener('keydown',function(e){
var ek = e.which;
if(ek==32){
for( var i = 0; i<=1 ;i+=0.01){
x+=i;
y+= Math.sin( counter );
counter+=inc;
basketball.style.left=x;
basketball.style.bottom=y;
}
}
});
*
{
transition: all 1s;
}
#basketball
{
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>
最佳答案
试试这个(函数调用自身):
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
var x = 0;
var y = 0;
var counter = 0;
var inc = Math.PI / 100 ;
function bounce(e, norecall){
var ek = e.which;
console.log('keydown');
if(ek==32){
for( var i = 0; i<=1 ;i+=0.01){
x+=i;
y+= Math.sin( counter );
counter+=inc;
basketball.style.left=x;
basketball.style.bottom=y;
}
}
if (!norecall) { //only runs the first time (when norecall == undefined)
bounce(e, true)
}
}
body.addEventListener('keydown',bounce); //call bounce on keypress
*
{
transition: all 1s;
}
#basketball
{
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>
这是在调用
bounce
函数且norecall为undefined
的情况下执行的。 !norecall
然后是true
,因此函数调用自身,这次是norecall
是true
,因此不会再次调用该函数,因此模拟了两次按下鼠标,从而解决了该问题。关于javascript - 简单的篮球运动Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51968667/