본문 바로가기
Programming/JavaScript

[JS] 글자 클릭하면 글자색이 바뀌는 자바 스크립트 / 클릭 이벤트 - 토끼는 개발자

by 토끼는개발자 2021. 8. 16.

 

 

1. onclick 이벤트 자바스크립트 소스 작성

마우스 클릭을 하고 나면 발생하게 할 이벤트가 있을 때 사용

예: 글자 클릭했을 때 다른 글자로 바뀌거나 글자색이 바뀌게 할 때

 

*작성코드 예시

<!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>
    <h1 class="texth1">토끼는 개발자</h1>
    <h4>글자 클릭하면 글자색이 바뀌는 자바 스크립트</h4>

    <script>
        var text = document.querySelector('.texth1');
        text.onclick = function() {
            text.style.color = 'purple';
        }

    </script>
</body>
</html>

 

2. 마우스 오른쪽 클릭 후 Open with Live Server

 

3. 마우스로 '토끼는 개발자' 클릭

 

4. 글자 색이 변경된 것을 확인

 

728x90