Web/JavaScript
[days06] 공 튀기기
다연
2020. 12. 16. 21:37
반응형
버튼을 누르면 공이 대각선 방향으로 움직이다가 끝에서 멈춘다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#container{
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate{
width: 50px;
height: 50px;
position: absolute;
background: red;
border-radius: 50%;
}
</style>
</head>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id="container">
<div id="animate"></div>
</div>
<script>
function myMove() {
var elem = document.querySelector("#animate");
var pos = 0;
var id = setInterval(function() {
if( pos == 350 ){
clearInterval(id);
}else{
pos++;
elem.style.left = pos+"px";
elem.style.top = pos+"px";
}
}, 5);
}
</script>
</body>
</html>
공튀기기 코딩
![]() |
![]() |
공이 벽에 부딪히면 튀긴다. Click Me 버튼을 누르면 좌측 상단에 있던 공이 움직이기 시작하고, Click make 버튼을 누르면 누를때마다 새로운 공이 생성된다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#container{
width: 400px;
height: 400px;
position: relative;
background: pink;
border: 1px solid gray;
}
.animate{
width: 50px;
height: 50px;
position: absolute;
background: skyblue;
border-radius: 50%;
border: solid 1px gray;
}
</style>
</head>
<body>
<p><button onclick="myMove('animate')">Click Me</button>
<button onclick="make()">Click make</button></p>
<div id="container">
<div id="animate" class="animate"></div>
</div>
<script>
function myMove( id ){
var elem = document.querySelector("#"+id);
var posX = 0 , posY = 0;
var x = 6, y = 9; // x,y 방향으로 한번에 이동할 거리 (내맘대로)
//클로저
var id = setInterval(function() {
if(posY >= 350 || posY <= 0) y *= -1;
if(posX >= 350 || posX <= 0) x *= -1;
posX += x;
posY += y;
//벗어나는것만큼 움직이지말자
if(posX<0) posX=0;
else if(posX>350) posX=350;
if(posY<0) posY=0;
else if(posY>350) posY=350;
elem.style.left = posX + "px";
elem.style.top = posY + "px";
}, 20);
}
//동적으로 버튼생성
var no = 1;
function make() {
var container = document.getElementById("container");
var newDiv = document.createElement("div");
newDiv.className = "animate"; //newDiv에 클래스 추가
newDiv.setAttribute("id", "animate"+no);
container.appendChild(newDiv);
myMove("animate"+no);
no++;
}
</script>
</body>
</html>
반응형