" if(x == 100)alert"不能与keydown功能结合使用?

时间:2014-06-05 12:04:17

标签: javascript if-statement jquery-animate alert keydown

我希望能够在对象位于底部时提醒用户。 我在这做什么错?

如果它更容易替换“nummer var”并且只检查顶部样式标签继续,因为它真的没关系! :)

小提琴:http://jsfiddle.net/Bs5Jn/

代码:

<head>
<script src="jquery-2.1.0.min.js"></script>
<style>
#object{position:absolute;
width:100px;
height:100px;
background-color:yellow;}
</style>
</head>
<script>
var nummer = 0;

$(document).keydown(function(e) {
    switch (e.which) {
    case 38:
        $("#object").stop().animate({
            top: "10" 
        }); 
        nummer = 0;
        break;
    case 40:
        $("#object").stop().animate({
            top: "200"
        }); 
        nummer = 100;
        break;
    }
})
 if (nummer == 100) {
        //do something it does have the protected class!
        alert("the object is at the bottom");
    }

</script>
<body>
<div id="object">
</div>


</body>

1 个答案:

答案 0 :(得分:1)

您应该将代码放在回调函数中,否则nummer将只是0

$(document).keydown(function(e) {
    switch (e.which) {
    case 38:
        $("#object").stop().animate({
            top: "10" 
        }); 
        nummer = 0;
        break;
    case 40:
        $("#object").stop().animate({
            top: "200"
        }); 
        nummer = 100;
        break;
    }

   if (nummer == 100) {
        //do something it does have the protected class!
        alert("the object is at the bottom");
    }

})