如何让这个 Javascript 函数正确迭代?

How can I get this Javascript function to iterate properly?

我正在将 Konami 复活节彩蛋合并到我的网站中以供娱乐;你输入 Konami 代码,它会播放《街头霸王》中的波动拳声音,背景中歌舞伎面具上的眼睛会亮起一秒钟。

它工作...有点。我有问题。输入 Konami 代码后,上述效果会在用户每次按键时重复出现。这不是为了那样做。我只希望效果在每次用户输入完整代码时立即关闭一次。

还有一个更小的问题,可以很好地解决。通过短暂切换具有所需效果的初始背景,面具的眼睛实际上会亮起来。然而,第一次这样做时,页面会在加载第二个背景时闪烁,但在后续迭代中不会闪烁。我想将第二个背景加载为 HTML 图像,并将其可见性设置为隐藏,但这没有用。

    <script>
        function PlaySound(path)
        {
            var audioElement = document.createElement('audio');
            audioElement.setAttribute('src', path);
            audioElement.play();
        }
        function resetBackground()
        {
            document.body.style.backgroundImage = "url('onics.png')";
        }
        function flashBackground()
        {
            document.body.style.backgroundImage = "url('onics_red.png')";
            setTimeout(resetBackground, 830);
        }
        if(window.addEventListener)
        {
            var kkeys=[],konami="38,38,40,40,37,39,37,39,66,65";
            window.addEventListener("keydown",function(e)
            {
            kkeys.push(e.keyCode);
            if(kkeys.toString().indexOf(konami)>=0)
                {
                    PlaySound('hadouken.wav');
                    flashBackground();
                }
            },true);
        }
    </script>

您可以添加一个标志

<script>
    var konamiPlayed = false;
    function PlaySound(path)
    {
        var audioElement = document.createElement('audio');
        audioElement.setAttribute('src', path);
        audioElement.play();
    }
    function resetBackground()
    {
        document.body.style.backgroundImage = "url('onics.png')";
        konamiPlayed = false;
    }
    function flashBackground()
    {
        document.body.style.backgroundImage = "url('onics_red.png')";
        setTimeout(resetBackground, 830);
    }
    if(window.addEventListener)
    {
        var kkeys=[],konami="38,38,40,40,37,39,37,39,66,65";
        window.addEventListener("keydown",function(e)
        {
            if (!konamiPlayed) {
                kkeys.push(e.keyCode);
                if(kkeys.toString().indexOf(konami)>=0)
                {
                    konamiPlayed = true;
                    PlaySound('hadouken.wav');
                    flashBackground();
                }
            }
        },true);
    }
</script>

编辑:

对于小问题,我认为这是因为浏览器仅在您要求时加载图像。所以,第一次需要一些时间。

您需要重置 kkeys 数组:

    if(window.addEventListener)
    {
        var kkeys=[],konami="38,38,40,40,37,39,37,39,66,65";
        window.addEventListener("keydown",function(e)
        {
        kkeys.push(e.keyCode);
        if(kkeys.toString().indexOf(konami)>=0)
            {
                kkeys = [];
                PlaySound('hadouken.wav');
                flashBackground();
            }
        },true);
    }