Div 클릭 시 색 변경 - Div keullig si saeg byeongyeong

Div 클릭 시 색 변경 - Div keullig si saeg byeongyeong

eleven

Follow

Jul 11, 2021

·

4 min read

[바닐라 자바스크립트] 글씨를 클릭할 때 마다 배경색과 글씨색을 변경하기

  1. 배운 기능

노마드 코더의 바닐라 자바스크립트를 보고서

텍스트를 클릭 했을때 텍스트 색상을 바꾸는 기능을 배웠습니다. 아래와 같이 ‘클릭'이라는 텍스트를 클릭 했을때 배경색과 글씨색이 바뀌도록 만들었습니다.

2. 어떻게 만들었는지 설명하기

#1. HTML 구조

<body>
<div class="body_container">
<h1 id="title">클릭</h1>
</div>
</body>

#2. 초기 CSS 설정

* {
margin:0;
padding:0;
}
.body_container {
transition: 0.5s ease-in-out;
width: 100%;
height:100vh;
display:flex;
align-items:center;
justify-content: center;
background-color: #0069c0;
color : #fff;

}
#title {
transition: 0.5s;
font-size : 64px;
}
.clicked {
background-color:#fff;
color:black;
}

#3. JavaScript

변수

const tit = document.querySelector('#title');
const bg = document.querySelector('.body_container');
const CLASS_CLICKED = "clicked";

함수 (기능)

VER1 —

toggle()

클래스 값을 토글링 하기

function handleClick() {
bg.classList.toggle(CLASS_CLICKED);
// CLASS_CLICKED = 'clicked'
// .clicked {background-color:#fff; color:black;}
}
  • classList는 DOMTokenList 객체로 요소의 클래스 이름을 반환합니다.
  • classList 사용은 공백으로 구분된 문자열인 element.className을 통해 엘리먼트의 클래스 목록에 접근하는 방식을 대체하는 간편한 방법이다.
  • toggle( String [, force] )하나의 인수만 있을 때: 클래스 값을 토글링한다. 즉, 클래스가 존재한다면 제거하고 false를 반환하며, 존재하지 않으면 클래스를 추가하고
    * {
    margin:0;
    padding:0;
    }
    .body_container {
    transition: 0.5s ease-in-out;
    width: 100%;
    height:100vh;
    display:flex;
    align-items:center;
    justify-content: center;
    background-color: #0069c0;
    color : #fff;

    }
    #title {
    transition: 0.5s;
    font-size : 64px;
    }
    .clicked {
    background-color:#fff;
    color:black;
    }
    0를 반환한다. 두번째 인수가 있을 때: 두번째 인수가
    * {
    margin:0;
    padding:0;
    }
    .body_container {
    transition: 0.5s ease-in-out;
    width: 100%;
    height:100vh;
    display:flex;
    align-items:center;
    justify-content: center;
    background-color: #0069c0;
    color : #fff;

    }
    #title {
    transition: 0.5s;
    font-size : 64px;
    }
    .clicked {
    background-color:#fff;
    color:black;
    }
    0로 평가되면 지정한 클래스 값을 추가하고 false로 평가되면 제거한다.

VER2 —

contains(), add(), remove()

값이 존재하는지 체크하고, 추가하거나 삭제하기

function handleClick() {
const hasClass = bg.classList.contains(CLASS_CLICKED);

if(hasClass) {
bg.classList.remove(CLASS_CLICKED);
} else {
bg.classList.add(CLASS_CLICKED);
}
}
  • contain 메소드는 classList의 메소드이다.
  • clicked클래스가 bg(body_container)에 포함되어있는지 Boolean값으로 리턴을 해준다. === contains(string) 지정한 string(클래스 값)이 요소(Element)의 class 속성에 존재하는지 확인한다.
  • classList는 읽기 전용이나, add()와 remove() 메서드를 이용하여 요소의 클래스를 추가하거나 제거할 수 있다.
  • IE9 및 이전 버전에서 지원되지 않는다. className 속성을 대체로 사용할 수 있다.
  • className : 요소의 클래스 이름(클래스 속성 값)을 설정하거나 반환합니다.

MDN > https://developer.mozilla.org/ko/docs/Web/API/Element/classList

끝으로…

이벤트 리스너를 통해 클릭할 때마다 handleClick 함수를 호출하기

  • 보통 초기화 하는데에 init() 함수를 많이 사용합니다.
function init() {
tit.addEventListener('click', handleClick);
}
init();

두 개의 버튼이 있습니다. 하나를 클릭하면 페이지를 새로 고치거나 또는 다른 버튼을 클릭하지 않는 한 회색에서 검은색으로 바뀌고 검은색으로 유지되기를 원합니다. 다른 버튼을 클릭하면 검정색으로 바뀌고 첫 번째 버튼은 회색으로 돌아가고 싶습니다. JS가 이를 위한 가장 좋은 방법이라고 생각하지만 어떻게 해야 할지 잘 모르겠습니다.

아래에 제 코드 중 일부가 있습니다.

HTML:

 <a id="button"></a>
 <a id="button"></a>

CSS:

6
#button {
display:inline‑block;
    height:10px;
    width:10px;
    border‑radius:10px;
    background‑color:gray;
}

미리 감사드립니다.


참조 솔루션

방법 1:

ID names should not be reused, change them to a class name instead, but they will still need an unique ID name each for us to apply Javascript logic to them.

html:

<a id="button1" class="button"></a>
<a id="button2" class="button"></a>

css:

.button 
            {
                display:inline‑block;
                height:10px;
                width:10px;
                border‑radius:10px;
            }

Javascript:

document.getElementById("button1").style.backgroundColor ="gray";
document.getElementById("button2").style.backgroundColor ="gray";


document.getElementById("button1").onclick = function(){
            this.style.backgroundColor ="black";
            document.getElementById("button2").style.backgroundColor ="gray";
        };

document.getElementById("button2").onclick = function(){
            this.style.backgroundColor ="black";
            document.getElementById("button1").style.backgroundColor ="gray";
        };

방법 2:

Here's an example I whipped up with no JavaScript ‑ instead I'm using two radio buttons that are styled depending on which one is "checked".

http://codepen.io/capitalq/pen/gLWLMK

.button {
  ‑webkit‑appearance: none;
  appearance: none;
  border: 0;
  background: gray;
  height: 50px;
  width: 50px;
  margin: 10px;
  outline: none;
  display: inline‑block;
  border‑radius: 50%;
}

.button:checked {
  background: black;
}
<input type="radio" class="button" name="buttons" id="button1" />
<input type="radio" class="button" name="buttons" id="button2" />

방법 3:

Use the jquery addClass function to add a class with a set background. The class will remain until there is a page load.

CSS Only aproach is :active, but it will not work on buttons, because the active property fades away once you release the click button. Maybe using an tag disguised as button may work, but will fade away once it losses the active state.