CSS와 자바스크립트

핸디·2021년 6월 24일
0

자바스크립트

목록 보기
3/4

JS에서도 CSS를 적용하거나 변경할 수 있지만
스타일 관련된건 CSS에서, 인터랙션과 관련된건 JS에서 하는게 좋다
(라고 니꼴라스쌤이 ..!)

click 이벤트로 h1속성 바꿔보기

const h1=document.querySelector("div.hello:first-child h1");
h1.addEventListener("click",handleTitleClick);

click me!라고 적힌 h1 element를 클릭하면 색깔이 blue에서 tomato로 변하게 해보자

1. 직접 써보기

-> currentColor, newColor이라는 변수를 사용해서 오류 줄이기

function handleTitleClick(){
    const currentColor=h1.style.color;
    let newColor;
    if(currentColor==="blue"){
        newColor="tomato";
    }
    else{
        newColor="blue";
    }
    h1.style.color=newColor;
}

2. CSS에 원하는 속성 만들어놓고 변경하기 + h1에 다른 클래스가 이미 적용되어 있을 때(sexy-font)

-> h1의 기본색깔 속성은 colorflowerblue로 해두고 자바스크립트에서 .active 클래스의 속성을 통해 바꿔보자

classList.contains , classList.add , classList.remove 알아보기

  • html
<!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">
    <link rel="stylesheet" href="style.css">
    <title>Momentum App</title>
</head>
<body>
    <div class="hello">
        <h1 class="sexy-font">click me!</h1>
        <h1>Grab me!2</h1>
        <h1>Grab me!3</h1>
    </div>
    
    <script src="app.js"></script>
</body>
</html>
  • CSS
h1 {
  color: cornflowerblue;
  transition: color 0.5s ease-in-out;
}

.active {
  color: tomato;
}

.sexy-font {
  font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
}
  • JS
function handleTitleClick(){
  const clickedClass="active";
  if(h1.classList.contains(clickedClass){
     h1.classList.add(clickedClass);
}
else{
  h1.classList.remove(clickedClass);
}
}

4. toggle -> 위의 기능을 한번에..!?

toggle: (이 예시에서) h1의 classList에 clickedClass 가 이미 있는지 확인해서 없다면 추가, 있다면 제거
--> 마치 스위치 같은 편리한 기능!

function handleTitleClick(){
  const clickedClass="active";
  h1.classList.toggle(clickedClass);
}

0개의 댓글