JavaScript

210924_setTimeout,setInterval,버튼,이미지

요옫 2021. 9. 24. 17:31

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style type="text/css">

div {

position: relative;  /*  relative 상대적 */

width: 100px;

height: 100px;

background-color: orange;

}

</style>

 

<script type="text/javascript">

 

var x=100;

var intervalId;

 

window.onload=function(){

//2추 뒤에 한번 호출

setTimeout(init,2000);

 

//0.5초마다 주기적으로 호출

    intervalId=setInterval(move,500);  //멈추려면 clearinterval도 필요하기에 대입함

}

 

function init() {

console.log('init호출');

/* box.style.left=x+'px';

box.style.top='100px'; */

 

box.style.background='pink';

}

 

function move() {

console.log('move호출');

x+=10;

box.style.left=x+"px";

}

 

//원위치

function initPos() {

box.style.left='100px';

x=100; //초기값 다시 적어주기

}

 

//멈춤

function stopPos() {

clearInterval(intervalId);  //타이머 멈춤

 

box.style.left='100px';

x=100; //초기값 다시 적어주기

alert("원위치후 타이머 멈춤")

}

 

//이미지출력

function imgWrite() {

imge1.src='../image/1.jpg';

imge2.src='../image/2.jpg';

}

</script>

</head>

<body>

 

<div id="box"></div>

 

<hr>

 

<!-- 버튼이벤트 -->

  <input type="button" value="원위치" onclick="initPos()">

  <input type="button" value="멈춤" onclick="stopPos()">

  <input type="button" value="이미지출력" onclick="imgWrite()">

 

<br>

 

<!-- 이미지출력 -->

  <img alt="" src="" name="imge1">

  <img alt="" src="" name="imge2">

</body>

</html>

 

 

박스 옆으로 이동

 

이미지출력 버튼 누른 후