id를 지정해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
    <title>자바스크립트</title>
    <link rel="stylesheet" type="text/css" href="index.css">
</head>
 
<body>
    <h1 id="title">This Works!</h1>
 
    <script src="index.js">
        
    </script>
</body>
 
</html>
cs



id="title" 를 가지고 와서 title 상수에 담는다.

handeClick() 함수를 만들어 id="title"을 클릭하면 색상이 blue로 변경되게 한다.

title.요소에 이벤트를 설정하여 클릭을 하면 함수가 실행되게 한다. 

1
2
3
4
5
6
7
8
9
10
const title = document.querySelector("#title");
 
// handleResize 함수를 만든다.
function handleClick(){
    title.style.color = 'blue';
}  
 
// id="title" 을 클릭하면 이벤트를 발생시킨다. 
// 이벤트의 내용은 handleClick()함수에 담고 있다.
title.addEventListener("click", handleClick);
cs




텍스트를 클릭하면 색상이 바뀜




기본색상이 있는 텍스트를 클릭하면 다른색으로 변경 다시 클릭하면 원래색으로 돌아오게하는 방법

직접적으로 css코드를 바꾸는 방법은 좋은 방법이 아니야.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const title = document.querySelector("#title");
 
const BASE_COLOR = "red";
const OTHER_COLOR = "blue";
 
//함수만들어준다.
function handClick(){
    const currentColor = title.style.color;
    if(currentColor === BASE_COLOR){
        title.style.color = OTHER_COLOR;
    }else{
        title.style.color = BASE_COLOR;
    }
}
 
//초기화값
function init(){
    title.style.color = BASE_COLOR;
    title.addEventListener("click",handClick);
}
 
//초기값 실행
init();
cs








텍스트를 클릭을 하면 클래스를 clicked를 넣어주는 방법


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const title = document.querySelector("#title");
 
const CLICKED_CLASS = "clicked";
 
function handClick(){
 
    const hasClass = title.classList.contains(CLICKED_CLASS);
 
    if(hasClass){
 
        title.classList.remove(CLICKED_CLASS);
 
    }else{
 
        title.classList.add(CLICKED_CLASS);
    }
}
 
function init(){
    title.addEventListener("click", handClick)
}
 
init();
cs


위의 코드를 아래의 toggle로 간단하게 변경할 수 있어!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const title = document.querySelector("#title");
 
const CLICKED_CLASS = "clicked";
 
function handClick(){
 
    title.classList.toggle(CLICKED_CLASS);
}
 
function init(){
    title.addEventListener("click", handClick)
}
 
init();
cs


+ Recent posts