Я просто знакомлюсь с jQuery, и у меня возникла идея сделать простой Super Mario Imitation. Я могу переместить Марио с помощью клавиш со стрелками, и я подумал, что смогу вымыть грибы, когда Марио переместится на место, но это, похоже, не работает, как я ожидал, если кто-то может указать мне в правильном направлении, я бы очень счастливый!
Здесь HTML:
<!DOCTYPE html>
<html>
<head>
<title>Super Mario!</title>
<link rel='stylesheet' type='text/css' href='stylesheet.css'/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<img class="mushroom" src="http://ih2.redbubble.net/image.6378228.5104/sticker,375x360.u2.png"/>
<img class="mario" src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg"/>
</body>
</html>
Здесь CSS:
img {
position: relative;
left: 0;
top: 0;
}
.mushroom {
position: relative;
left: 300;
top: 200;
width: 48px;
height: 48px;
}
И здесь jQuery:
$(document).ready(function() {
// Keydown function to move mario
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
// Left arrow key pressed
case 37:
$('.mario').animate({left: "-=10px"}, 'fast');
break;
// Up Arrow Pressed
case 38:
$('.mario').animate({top: "-=10px"}, 'fast');
break;
// Right Arrow Pressed
case 39:
$('.mario').animate({left: "+=10px"}, 'fast');
break;
// Down Array Pressed
case 40:
$('.mario').animate({top: "+=10px"}, 'fast');
break;
}
// On Mario arrival remove Mushroom
$(document).on('keydown', '.mario', function(e){
var x = e.clientX - this.offsetLeft,
y = e.clientY - this.offsetTop;
if (x > 300 && x < 400 && y > 200 && y < 300) {
$('.mushroom').fadeOut('slow');
}
});
});
});
Сначала я попробовал с инструкцией IF, проверяющей Mario css на позицию - он не работает, но, чем я понял, что css, вероятно, не переписан на keydown. Поэтому я застрял:/
Идея заявления IF выглядела так:
// On Mario arrival remove Mashroom
$(document).on('keydown', '.mushroom', function() {
if($('.mario').css("left")=="300" && ("top")=="200") {
$('.mashroom').animate({left: "+=10px"}, 'fast');
}
});
Спасибо за помощь!
Отсутствует
$('.mario').css("top")
if($('.mario').css("left")=="300" && $('.mario').css("top")=="200") {
// ^ ^
keyup