본문 바로가기

Programming/Javascript

캐릭터 움직이기

img.zip
0.24MB

move_horse.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/moveImgStyle.css" />
</head>
<body>
	<div id="bg">
		<img src='img/horse.png'>
		<button class='btn left'>LEFT</button>
		<button class='btn right'>RIGHT</button>
	</div>
	<script type="text/javascript">
		var img = document.querySelector('img');
		var left = document.querySelector('.btn.left');
		var right = document.querySelector('.btn.right');
		var c = 0;
		var body = document.querySelector('body');

		left.addEventListener('click', leftMove);
		right.addEventListener('click', rightMove);
		body.addEventListener('keydown', move);

		function leftMove() {
			if (c < 1200) {
				c += 30;
				img.style.right = c + 'px';
			}
		}

		function rightMove() {
			if (c > 0) {
				c -= 30;
				img.style.right = c + 'px';
			}
		}

		function move(event) {
			var input = event.keyCode;
			if (input == 37) {
				leftMove();
			} else if (input == 39) {
				rightMove();
			}
		}
	</script>
</body>
</html>

 

Web Content > css > moveImgStyle.css

@charset "UTF-8";

#bg {
	width: 1280px;
	height: 720px;
	background-image: url('../img/bg.png');
	background-size: cover;
	background-repeat: no-repeat;
	position: relative;
}

img {
	width: 70px;
	height: 170px;
	position: absolute;
	right: 0px;
	bottom: 200px;
}

.btn {
	width: 170px;
	height: 100px;
	border: none;
	font-size: 20px;
	font-weight: bold;
	position: absolute;
	color:white;
	background: rgba(0,0,0,0.3)
}

.left{
	right:600px;
	bottom:25px;
}

.right{
	right:400px;
	bottom:25px;
}