Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

도도의 IT이야기

[jQuery] CSS/class 바꾸는 방법 본문

IT/자바스크립트

[jQuery] CSS/class 바꾸는 방법

도도버드 2020. 5. 12. 21:11

지금까지 여러 jQuery method들을 알아봤는데요.

 

이번엔 CSS를 바꾸는 방법대해서 알아보겠습니다. 당연히 CSS를 바꾸는 방법은 .css  메소드를 사용하겠죠. 

하지만 좀더 자세히 알아봅시다.

 

일단 HTML코드를 만듭시다.

<style>
div{
  color:red;
  background-color:blue;
  padding:2rem;
}
</style>

<div>
   <ul>
     <li>blah</li>
   </ul>
</div>

이런 코드가 있다고 해봅시다.

 

여기서 먼저 div element의 color속성을 알고 싶다! 하면 이렇게 합시다.

$('div').css('color');//return red

이렇게 선택한 element의 css attribute을 인자로 보내면 value를 리턴합니다

 

그럼 선택한 css attribute을 바꾸려면? 쉽습니다. 그저 두개의 인자를 보내면되죠.

$('div').css('color','black');

이렇게 색을 바꿀 수 있습니다. 근데 바꾸고 싶은 css가 많다면 어떻게 할까요? 우리가 전에 배운 chaining을 써봅시다.

$('div').css('color','black').css('background-color','white').css('padding','3rem');

이런식으로 사용해야 하겠죠? 그러면 코드가 너무 길어지기 때문에 적절하지 않습니다. 그래서 우리는 object를 사용하여 위의 코드를 짧게 정리할 수 있습니다.

$('div').css({
  'color':'red',
  backgroundColor:'blue',//"background-color" 이렇게 쓸라면 quote를 해야함
  padding:'3rem'
})

이런 식으로 정리 할 수 있습니다.

 

CLASS

 

이제 class를 바꾸는 방법을 알아보자.

 

class는 attribute이기 때문에 attr(), removeAttr() 메소드를 쓸 수 있지만 class만 바꾸는 일이 많아서 따로 메소드를 만드거 같다.

 

class 바꾸기 위해 .removeClass, addClass, toggleClass를 사용할 수 있다.

 

HTML코드를 써보자

 

<style>
.wrapper{
  width:950px;
  margin:auto;
}
</style>

<a class="removeBtn">remove</a>
<section>
   <div class=wrapper>


   </div>
   
   <div class="something">
   
   </div>
   
</section>

이런 코드가 있다고 해보자 div는 wrppaer클래스에 의해 950px으로 화면 중앙에 위치한다. 이제 wrapper 클래스를 없애보자

 

$('section .wrapper').removeClass('wrapper');

이렇게 치면 wrapper 클래스가 없어지고 그 결과로 인해 div안의 element들이 화면 전체를 차지하게 되겠죠.

 

다시 더해봅시다.

$('section div:first').addClass('wrapper');//또는
$('section div:first-child').addClass('wrapper');

이렇게 하면 됩니다. 아까 전처럼 .wrapper로 선택할수 없겠죠? wrapper class를 remove했으니

 

그럼 이제 이런 HTML을 상상해봅시다

<style>
.wrapper{
  width:950px;
  margin:auto;
  height:0;
  overflow:none;
}
.open{
  height:auto;
}
</style>

<button class="removeBtn">remove</button>
<section>
   <div class="wrapper">


   </div>
   
   <div class="something">
   
   </div>
   
</section>

이러한 코드가 있다고 합시다.

지금 div class="wrapper"은 height가 0이기 때문에 화면에서 보이지 않습니다. 그렇기에 .open 클래스를 더하여 height를 overwrite합시다.

 

우리는 저 removeBtn에 이벤트핸들러를 달아서 open class를 더하고 빼주는 toggle을 달아봅시다.

 

let button = $('removeBtn');
let wrapper = $('section .wrapper')


button[0].addEventListener('click',function(){//unwrap을 하지 않으면 JS의 메소드를 못씀
   
   wrapper.toggleClass('open');
   return false;//false를 리턴하는 button의 default behavior(새로고침)을 prevent하기 위함 

})

위처럼 할 수 있다.

근데 return false 말고 event.preventDefault()를 사용해도됨