0

在我的动画中,“下雨”的点是随机颜色的,我希望能够通过按 ENTER 来更改颜色。对于按键我使用以下代码:

    $(document).keypress(function(event){
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13'){
            // change variables for the colors
        }
    });

正如我所看到的,代码应该没有任何问题,但是按 ENTER 时没有任何反应。如果有人可以在这里帮助我,我会很高兴!

你可以在这里找到代码:http: //jsfiddle.net/GsBcz/

4

1 回答 1

1

为什么要在每个动画调用上绑定一个事件?[event.which] 也是 jQuery 检测鼠标和按键事件的跨浏览器方式。

这应该有帮助,

小提琴

HTML:

<html>
<head>
        <title>Raining dots</title> 
        <link href='http://fonts.googleapis.com/css?family=Give+You+Glory' rel='stylesheet' type='text/css'> 
        <link href='http://fonts.googleapis.com/css?family=Gloria+Hallelujah' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" type="text/css" media="screen" href="css/style.css">
           <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> 
        <script type="text/javascript" src="js/external.js" ></script>
</head>
        <body id="bg">
        </body>
</html>​

JAVASCRIPT:

var Capsule = {
    init: function() {

        this.c1 = 256, this.c2 = 220, this.c3 = 225;
        Capsule.callDots();
    },

    callDots: function() {

        window.setInterval(function() {
            Capsule.animateDots(Capsule.c1, Capsule.c2, Capsule.c3);
        }, 10);
    },

    animateDots: function() { 

        var theWidth = $(window).width(),
            theHeight = $(window).height(),
            randomEntry = Math.ceil(Math.random() * theWidth),
            preRandomDotSize = Math.ceil(Math.random() * 40),
            randomDotSize = preRandomDotSize + 50;

        var dotName = 'dot-' + randomEntry,
            color1 = Math.ceil(Math.random() * Capsule.c1),
            color2 = Math.ceil(Math.random() * Capsule.c2),
            color3 = Math.ceil(Math.random() * Capsule.c3),
            colors = 'rgb(' + color1 + ',' + color2 + ',' + color3 + ')';

        $('<div />', {
            text: '.',
            id: dotName,
        }).appendTo('body').addClass('theDots').css('left', randomEntry).css('font-size', randomDotSize).css('color', colors).animate({
            "top": "+=" + theHeight
        }, 5000, function() {});
    }
};
$(document).ready(function() {
    Capsule.init();
}).keypress(function(event) {
    if (event.which == '13') {
        Capsule.c1 += 2, Capsule.c2 += 4, Capsule.c3 += 6;
    }
});​

CSS:

body {
    font: 14px / 1.5em 'Gloria Hallelujah', cursive;
}

.theDots{
        position:absolute;
        top:-50px;
        left:0px;
        z-index:10;
        position:block;
}​
于 2012-06-08T14:37:42.953 回答