在我的动画中,用随机颜色“下雨”点,我希望能够通过按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/
答案 0 :(得分:1)
为什么要在每个动画调用中绑定事件?另外[event.which]是jQuery的crossbrowser方式来检测鼠标和键事件。
这应该有帮助,
<强> 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;
}