반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

ZeroToHunnit Coding

[Javascript] 특정 섹션에 마우스 올리면 변하는 커서 본문

JAVASCRIPT

[Javascript] 특정 섹션에 마우스 올리면 변하는 커서

0에서100 2024. 1. 19. 14:18
728x90
반응형

위와 같이 평소엔 마우스 커서를 따라다니는 작은 원이었다가 특정 섹션에 마우스를 올리면 VIEW가 나오는 큰 원으로 변하는 커서를 만들어보았다.

 

HTML

  <div class="section1"></div>
  <div class="section2"></div>
  <div class="cursor">
    <p>VIEW</p>
  </div>

커서에 미리 VIEW를 넣어 놓는다.

 

CSS

.cursor{
  position: absolute;
  width: 30px;
  height: 30px;
  background-color: black;
  border-radius: 50%;
  z-index: 9999;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cursor p{
  color: white;
  font-size: 40px;
  font-weight: bold;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s;
}

.section1{
  position: absolute;
  top: 200px;
  left: 100px;
  width: 30%;
  height: 50%;
  background-color: blue;
}

.section2{
  position: absolute;
  top: 200px;
  left: 700px;
  width: 30%;
  height: 50%;
  background-color: yellow;
}

.section1:hover ~ .cursor,
.section2:hover ~ .cursor{
  width: 150px;
  height: 150px;
}

.section1:hover ~ .cursor p,
.section2:hover ~ .cursor p{
  opacity: 1;
  visibility: visible;
}

 

JAVASCRIPT

window.addEventListener('pointermove',function(e){
  document.querySelector('.cursor').animate({
    left: `${e.clientX}px`,
    top: `${e.clientY + window.scrollY}px`
  },{duration: 600, fill:'forwards'})
})

자바스크립트와 CSS를 묶어서 설명하자면 cursor div를 position:absolute로 띄워 자바스크립트로 left값과 top값을 마우스 커서가 이동하는 값으로 움직이게 animate함수를 썼다. 그리고 섹션에 마우스를 hover하면 원의 width값과 height값을 조절하고 VIEW를 보여주게 하였다.

 

여기서 HTML 요소를 보면 부모 자식 요소가 아닌 형제요소인 것을 확인할 수 있다. 그래서 CSS에서 hover를 넣어주었을 때 '~'를 볼 수 있는데 이는 형제 중 위에서 밑으로만 적용이 가능하다. 만약 cursor div가 제일 위에 있었다면 '~'를 써도 적용이 되지 않는 모습을 볼 수 있다.

728x90
반응형