개발

버튼 클릭시 기능 주기 (간단한 카운팅 예제) 본문

Frontend/JavaScript

버튼 클릭시 기능 주기 (간단한 카운팅 예제)

Study 2021. 3. 5. 22:30

 

간단한 카운터기능과

자동으로 그 기능을 반복해주는 기능을 만들어 봅시다! 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>카운터</title>
</head>
<body>
    <button onClick="setCount()">카운터 증가</button>
    <button onClick="auto();this.disabled=true">자동 증가</button>
</body>
</html>
cs

 

버튼을 먼저 만들어 주고

onClick 기능에 함수명을 각각 setCount()와 auto()로 줍니다! 

자동버튼은 한번만 클릭되고 비활성화 시키기 위해 뒤에 this.disable=true 옵션도 넣어줍니다.

 

 

눌렀을 때 비황성화 되는지도 잘 확인 해 주세요.

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>카운터</title>
<style>
    input{
        height: 500px;
        width: 600px;
        background-color: dodgerblue;
        color: white;
        font-size: 200px;
        text-align: center;
    }
</style>
</head>
<body>
    <button onClick="setCount()">카운터 증가</button>
    <button onClick="auto();this.disabled=true">자동 증가</button>
    <br>
    <input id="txt" type="text" value="0">
</body>
</html>
cs

 

input 기능으로 숫자를 넣어주시고! 상단부에 style 시트로 원하는데로 꾸며줍시다!

 

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>카운터</title>
<style>
    input{
        height: 500px;
        width: 600px;
        background-color: dodgerblue;
        color: white;
        font-size: 200px;
        text-align: center;
    }
</style>
<script>
var x=0;
function setCount(){
    x=x+1
    document.querySelector("#txt").value=x
}
function auto(){
    setInterval("setCount()"50);
}
</script>
</head>
<body>
    <button onClick="setCount()">카운터 증가</button>
    <button onClick="auto();this.disabled=true">자동 증가</button>
    <br>
    <input id="txt" type="text" value="0">
</body>
</html>
cs

x 라는 변수를 하나 만들어 주고 ~ 

setCount() 변수에는  x=x+1 (x++ 로 대체가능)

document.querySelector("#txt").value=x

문서안 txt라는 아이디의 쿼리를 잡아서 벨류값을 변수 x로 바꾸어라!

 

완성입니다.!