当我按下键盘上的键时,keydown事件会多次触发

时间:2015-07-30 13:02:43

标签: javascript jquery html5 css3

这是一个jsfiddle链接http://jsfiddle.net/lotusgt1suri/a1gc1h4q/

我的问题是,当我按 a s d [一次一键]键时,keydown事件会触发多个次。

我希望当我按 a s d [一次一个]键时,keydown事件只会触发一次,也是我已经生成随机苹果,在我的例子中有苹果,所以当顶级苹果显示 d keydown事件只触发一次然后点击苹果,当中间苹果显示 a 事件只触发一次并击中苹果等等......

我也发布了整个代码......

抱歉我的英语不好。

以下是我的代码。

的index.html

.ring{
  position: relative;
  z-index: 1;
} 
.hand{
  position: absolute;
  z-index: 2;
  top: 150px;
  left: 200px;
  height:70px;
  width:100px;
} 

.game-btn{
  border-radius: 100px;
  width: 70px;
  height: 70px;
}

.center{
  text-align: center;
}


.box {
  width: 50px;
  height: 50px;
  position: absolute;
  z-index: 3;
  top: 0px;
  left: 460px;
} 

#timerDiv
{
  width: 180px;
  height: auto;
  font-weight: 800;
  font-size: 1.5em;
  border-radius: 25px;
  background-color: dodgerblue;
  color: #fff;
  text-align: center;
}

ems.css

// KEYPRESS EVENT
$(document).bind('keydown', 'a', function(){
    var right = $(".hand");
    right.animate({width: '300px'}, 50);
    right.animate({width: '100px'}, 50);
});


$(document).bind('keydown', 's', function(){
    var down = $(".hand");
    down.animate({left: '200px', top:'220px', width: '300px'}, 50);
    down.animate({left: '200px', top:'150px', width: '100px'}, 50);
});

$(document).bind('keydown', 'd', function(){
    var up = $(".hand");
    up.animate({left: '200px', top:'50px', width: '300px'}, 50);
    up.animate({left: '200px', top:'150px', width: '100px'}, 50);
}); 

// RANDOM APPLE
(function loop() {
    setTimeout(function () {
        var random = Math.floor(Math.random() * $('.box').length);
        $('.box').hide().eq(random).show();
        loop()
    }, 500);
}());



// TIMER
$(document).ready(function(){
    var timer = null;
    var time = 0;
    $('#mybutton').click(function() {
        time = 120;      
        showTimer();
        timer = setInterval(showTimer, 1000);
    });

    function showTimer() {
        if (time < 0) {
            clearInterval(timer);
            return;
        }
        function pad(value) {
            return (value < 10 ? '0' : '') + value;
        }
        function stop() {
            clearTimeout(timer);
        };
        $('#stop').click(stop);
        $('#timerDiv').text("Time:- " + Math.floor(time / 60) + ':' + pad(time % 60));
        time--;
    }
});

boxing.js

var windowObjectReference = window.open(strUrl, strWindowName, [strWindowFeatures]);

window.open(fullscreen=Yes);

1 个答案:

答案 0 :(得分:1)

主要问题是您没有从事件中获取密钥代码。因此,对于您的听众,每个动画都是通过每个按键完成的。有3个听众,完成了3个动画。 您可以将所有功能移动到一个功能中,并使用密钥代码进行切换。要获取某些字符的密钥代码,您只需添加

即可
console.log(e.which)

这是更新的小提琴http://jsfiddle.net/a1gc1h4q/2/