My Melody Kawaii

JAVASCRIPT/마우스 이펙트

마우스를 글씨에 가져가면 나타나는 효과 만들어보기!

younajeong 2023. 3. 20. 23:52

“ 지연되는 프로젝트에 인력을 더 투입하면 오히려 더 늦어진다. ”

- Frederick Philips Brooks
Mythical Man-Month 저자
728x90

마우스 이펙트 01

 

오늘은 마우스에 이펙트 효과를 입혀봤습니다. 마우스 이펙트 효과(Mouse Effect)란 마우스를 움직이는 동안 마우스 포인터가 가지는 효과를 말합니다. 이는 주로 웹 사이트나 앱 디자인에서 사용되며, 마우스 움직임에 반응하는 다양한 효과가 있습니다.

 

예를 들어, 마우스를 움직이면 배경색이 바뀌거나, 이미지가 움직이거나, 텍스트가 확대되거나 축소되는 등의 효과가 있습니다. 이를 통해 사용자의 마우스 조작에 반응하여 화면을 보다 생동감 있게 만들어줍니다.

 

마우스 이펙트는 웹 개발에서 CSS, JavaScript 등을 이용하여 구현됩니다. 사용자 경험을 높이기 위해 다양한 마우스 이펙트를 적용할 수 있습니다.

 

HTML코드

<body class="img01 bg01 font01">
    <header id="header">
        <h1>Javascript mouseEffect01</h1>
        <p>마우스 이펙트 -마우스 따라다니기</p>
        <ul>
            <li class="active"><a href="mouseEffect01.html">1</a></li>
            <li><a href="mouseEffect02.html">2</a></li>
            <li><a href="mouseEffect03.html">3</a></li>
            <li><a href="mouseEffect04.html">4</a></li>
            <li><a href="mouseEffect05.html">5</a></li>
            <li><a href="mouseEffect06.html">6</a></li>
        </ul>

    </header> 
    <!-- //header -->

    <main id="main">
        <div class="mousee__wrap">
            <div class="mouse__cursor"></div>
            <div class="mouse__text">
                <p><span class="s1">Problems</span> are not <span class="s2">stopsings</span>, they are <span class="s3">guidelines.</span></p>
                <p><span class="s4">문제</span>는 <span class="s5">정지신호</span>가 아니라 <span class="s6">가드라인</span>이다.</p>
            </div>
        </div>
        <div class="mouse__info">
            <ul>
                <li>clientX : <span class="clientX">0</span>px</li>
                <li>clientY : <span class="clientY">0</span>px</li>
                <li>offsetX : <span class="offsetX">0</span>px</li>
                <li>offsetY : <span class="offsetY">0</span>px</li>
                <li>pageX : <span class="pageX">0</span>px</li>
                <li>pageY : <span class="pageY">0</span>px</li>
                <li>screenX : <span class="screenX">0</span>px</li>
                <li>screenY : <span class="screenY">0</span>px</li>
            </ul>
        </div>

    </main>
    <!-- //main -->

    <footer id="footer">
        <a href="mailto:jeongyouna_@naver.com">jeongyouna_@naver.com</a>
    </footer>  
    <!-- //footer -->

CSS코드

/* reset */
@import url('https://webfontworld.github.io/hallym/Hallym.css');
@import url('https://webfontworld.github.io/suncheon/Suncheon.css');
@import url('https://webfontworld.github.io/Poppins/Poppins.css');
@import url('https://webfontworld.github.io/kt/YUniverse.css');
@import url('https://webfontworld.github.io/TheJamsil/TheJamsil.css');
@import url('https://webfontworld.github.io/NanumBarunGothic/NanumBarunGothic.css');
@import url('https://webfontworld.github.io/busan/Busan.css');
@import url('https://webfontworld.github.io/GothicA1/GothicA1.css');
@import url('https://webfontworld.github.io/jeju/JejuGothic.css');
@import url('https://webfontworld.github.io/amore/AritaBuri.css');

* {
    margin: 0;
    padding: 0;
    color: #fff;
}

*,*::before, *::after {
    box-sizing: border-box;
}
a{
    text-decoration: none;
    color: #222;
}
h1,h2,h3,h4,h5,h6 {
    font-weight: normal;
}
li, ul, ol {
    list-style: none;
}
img {
    vertical-align: top;
    width: 100%;
}
em {
    font-style: normal;
}
.font01 {
    font-family: 'Hallym';
}
.font02 {
    font-family: 'Suncheon';
}
.font03 {
    font-family: 'Poppins';
}
.font04 {
    font-family: 'YUniverse';
}
.font05 {
    font-family: 'TheJamsil';
}
.font06 {
    font-family: 'NanumBarunGot';
}
.font07 {
    font-family: 'Busan';
}
.font08 {
    font-family: 'GothicA1';
}
.font09 {
    font-family: 'JejuGothic';
}
.font10 {
    font-family: 'AritaBuri';
}
body {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background-position: center center;
    background-size: cover;
}
body.img01 {
    background-image: url(../img/mouseEffect01-min.jpg);
}
body.img02 {
    background-image: url(../img/mouseEffect02-min.jpg);
}
body.img03 {
    background-image: url(../img/mouseEffect03-min.jpg);
}
body.img04 {
    background-image: url(../img/mouseEffect04-min.jpg);
}
body.img05 {
    background-image: url(../img/mouseEffect05-min.jpg);
}
body.img06 {
    background-image: url(../img/mouseEffect06-min.jpg);
}
body.img07 {
    background-image: url(../img/mouseEffect07-min.jpg);
}
body.img08 {
    background-image: url(../img/mouseEffect08-min.jpg);
}
body.img09 {
    background-image: url(../img/mouseEffect09-min.jpg);
}
body.img10 {
    background-image: url(../img/mouseEffect10-min.jpg);
}
body::after {
    content: '';
    position: absolute;
    left: 0; top: 0;
    width: 100%;
    height: 100vh;
    background-color: rgba(63, 14, 30, 0.87);
    z-index: -1;
}
body.bg01::after {
    background-color: rgba(17, 97, 79, 0.65);
}
body.bg02::after {
    background-color: rgba(53, 19, 67, 0.87);
}
body.bg03::after {
    background-color: rgba(66, 12, 71, 0.87);
}
body.bg04::after {
    background-color: rgba(71, 12, 34, 0.87);
}
body.bg05::after {
    background-color: rgba(68, 12, 12, 0.87);
}
body.bg06::after {
    background-color:  rgba(12, 54, 68, 0.87);
}
body.bg03::after {
    background-color: rgba(12, 68, 65, 0.87);
}
body.bg07::after {
    background-color: rgba(14, 54, 61, 0.87);
}
body.bg08::after {
    background-color: rgba(14, 61, 22, 0.87);
}
body.bg09::after {
    background-color: rgba(14, 19, 48, 0.87);
}
body.bg10::after {
    background-color: rgba(63, 14, 30, 0.87);
}

/* header */

#header {
    padding: 20px;
    position: absolute;
    left: 0;
    top: 0;
}
#header h1 {
    margin-bottom: 10px;
}
#header a {
    color: #fff;
}
#header p {
    margin-bottom: 10px;
}
#header li {
    display: inline-block;
}
#header li a {
    border: 1px solid #fff;
    width: 30px;
    height: 30px;
    display: inline-block;
    color: #fff;
}
#header li.active a {
    background-color: #fff;
    color: #000;
}

/* footer */
#footer {
    position: absolute;
    right: 0;
    bottom: 0;
    padding: 20px;
}
#footer a {
    color: #fff;
}

HTML & CSS

  • 전체적인 HTML구조를 만들어 줍니다.
  • CSS는 따로 설정해서 이미지와 폰트를 설정해준 후 mouse 에 필요한 효과들은 HTML에 style속성을 사용해서 만들어줍니다.
  • 마우스 효과를 주기위해 cousor를 대신할 둥근 원을 만들어 줍니다.

 

자바스크립트

const cursor = document.querySelector(".mouse__cursor");

        window.addEventListener("mousemove",function(e){
            cursor.style.left = e.clientX -25 + "px";
            cursor.style.top = e.clientY -25 + "px";
        });

         document.querySelector(".s1").addEventListener("mouseover", function(){
             cursor.classList.add("s1");
         });
         document.querySelector(".s1").addEventListener("mouseout", function(){
             cursor.classList.remove("s1");
         });

         document.querySelector(".s2").addEventListener("mouseover", function(){
             cursor.classList.add("s2");
         });
         document.querySelector(".s2").addEventListener("mouseout", function(){
             cursor.classList.remove("s2");
         });

         document.querySelector(".s3").addEventListener("mouseover", function(){
             cursor.classList.add("s3");
         });
         document.querySelector(".s3").addEventListener("mouseout", function(){
             cursor.classList.remove("s3");
         });

        document.querySelector(".s4").addEventListener("mouseover", function(){
            cursor.classList.add("s4");
         });
         document.querySelector(".s4").addEventListener("mouseout", function(){
             cursor.classList.remove("s4");
         });

         document.querySelector(".s5").addEventListener("mouseover", function(){
             cursor.classList.add("s5");
         });
         document.querySelector(".s5").addEventListener("mouseout", function(){
             cursor.classList.remove("s5");
         });

         document.querySelector(".s6").addEventListener("mouseover", function(){
             cursor.classList.add("s6");
         });
         document.querySelector(".s6").addEventListener("mouseout", function(){
             cursor.classList.remove("s6");
         });

        //for 문
         for(let i=1; i<=6; i++){
             document.querySelector(".s"+i).addEventListener("mouseover", function(){
             cursor.classList.add("s"+i);
       	 });
         document.querySelector(".s"+i).addEventListener("mouseout", function(){
             cursor.classList.remove("s"+i);
         });
         }

        //for Each
         document.querySelectorAll (".mouse__text span").forEach(function(span, num){
             span.addEventListener("mouseover", function(){
             cursor.classList.add("s"+(num+1));
         });
             span.addEventListener("mouseout", function(){
             cursor.classList.remove("s"+(num+1));
         });
         })

        //getAttribute() 
        document.querySelectorAll(".mouse__text span").forEach(function(span){
            let attr = span.getAttribute("class");
            console.log(attr)
            //attr = s1, s2, s3, s4, s5, s6
            span.addEventListener("mouseover",function(){
                cursor.classList.add(attr);
            });
            span.addEventListener("mouseout",function(){});
                cursor.classList.remove(attr);
        });

    </script>

자바스크립트

 

01. s1부터 s6에 출력될 값을 하나하나 출력해 보도록 하겠습니다.

"mouseover"이라는 이벤트를 사용하는데 요소위에 포인터 요소 위치에 있을때 사용되는 효과입니다.

  1. const cursor = document.querySelector(".mouse__cursor"); 먼저 선택자를 .mouse__cursor를 선택해줍니다.
  2. 6개의 이미지를 만들고 6개의 폰트를 만들었기 때문에 6개의 effect가 존재합니다. 먼저 마우스 커서를 대신할 동그란 원을 움직여 주기위해 함수를 이용해서  
  3. window.addEventListener("mousemove",function(e){
                cursor.style.left = e.clientX -25 + "px";
                cursor.style.top = e.clientY -25 + "px";
            });   를 만들어 줍니다.
  4. 여기서 clientX , clientY는 브라우저 기준으로 X의 좌표값과 Y의 좌표값입니다.
  5. 처음에 사용할 자바스크립트는 선택자를 사용해서 s1부터 s6까지 값이 나올 수 있게 끔 입력해 주는데 퀴즈이펙트때 배웠던 스크립트를 기반으로 querySelector를 써서  
  6. document.querySelector(".s1").addEventListener("mouseover", function(){
                 cursor.classList.add("s1");
             });
             document.querySelector(".s1").addEventListener("mouseout", function(){
                 cursor.classList.remove("s1"); 를 만들어 줍니다.
  7. 여기서 document.querySelector()는 요소 선택자로 선택자를 선택할 때 사용하며 classList.add는 클래스 요소 선택자로 클래스를 추가하고 remove는 지워주는 것을 말합니다.
  8. 저렇게 6번을 똑같이 사용해서  s1번부터 s6번까지 값이 출력되었습니다.

 

 

02.  for문을 사용해서 값을 출력해 보도록 합니다.

  1. for문의 형식을 써줍니다. for (let i=0; i<=0; i++){};
  2. 이 형식에 우리는 1번부터 6번까지 출력을 해야하기 때문에 i=0자리에는 i=1; i<=0;자리에는 6번까지 출력을 해줘야 하므로 i<=6; i++로 형식을 만들어 준 후 중괄호 안에는 우리가 처음에 값을 출력했던 document.querySelector를 가져옵니다. 
  3. 가져온 값 안에는 (".s1")과 같이 존재할 텐데 숫자는 for문을 사용해서 뽑았으니 괄호 안에 문자열 "."을 써주고 +i를 입력하면
  4. for문을 사용해서 s1부터 s6까지의 값이 출력 됩니다.

 

03.  forEach()문을 사용해서 값을 출력해 보도록 합니다.

  1. forEach()는 다중이 즉 다중 선택자를 사용할 때 출력해주는 실행문 입니다.
  2. 그래서 선택자를 쓸 때 document.querySelectorAll이라고 써줍니다. 
  3. forEach는 앞에 변수를 나타내야 하는데 그 앞에 선택자 document.querySelectorAll (".mouse__text span")를 써준후 .forEach(function(){}); forEach문을 적어줍니다. 중괄호 안에는
  4. document.querySelector(".s1").addEventListener("mouseover", function(){
                 cursor.classList.add("s1");
             });
             document.querySelector(".s1").addEventListener("mouseout", function(){
                 cursor.classList.remove("s1");  for문에서 사용했던 요소 선택자와 클래스 선택자를 가져옵니다.
  5. forEach문에서는 function앞 ()괄호 안에 요소,인덱스값,객체가 들어갈 수 있습니다. 
  6. 현재 우리가 출력해야하는 값이 span안에 있는 mouse__text요소의 값입니다. 그래서 괄호 안에는 span을 써줍니다.
  7. 그리고 document.querySelector(".s1")span에 포함되어 있는 요소이므로 그 자리를 span이라고 적어줍니다.
  8. 그 다음에 출력되어야 하는게 숫자이므로 span 옆에 num을 써줍니다.
  9. 문자열 "s"와 숫자는 num+1로 증가 되게끔 나올 수 있도록 설정해주고 num+1이 우선순위가 될 수 있도록 ( )괄호 안에 넣어줍니다.
  10. forEach문을 사용해서 s1부터 s6의 값이 출력됩니다.

 

04. getAttribute()을 사용해서 값을 출력해 보도록 합니다.

getAttribute()은 해당 요소에 지정된 값을 반환하는 하는 요소의 속성을 가져오는 속성입니다.

 

  1. forEach문을 사용하는데 안에 반환하는 요소를 변수를 선언하여서 그 안에 값을 저장하는 것입니다.
  2. document.querySelectorAll(".mouse__text span").forEach(function(span){
                let attr = span.getAttribute("class")를 써주면 attr안에 s1, s2, s3, s4, s5, s6의 값이 저장되어 있습니다.
  3. document.querySelector(".s1").addEventListener("mouseover", function(){
                 cursor.classList.add("s1");
             });
             document.querySelector(".s1").addEventListener("mouseout", function(){
                 cursor.classList.remove("s1");       // 괄호 안에 attr을 적어준다면 요소의 속성을 가져와서 값이 출력됩니다.

 

CSS

 <style>
        .mouse__wrap {
            cursor: none;
        }
        .mouse__cursor {
            position: absolute;
            left: 0%;
            top: 0%;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            border : 3px solid #fff;
            background-color: rgba(225,225,225,0.1);
            user-select: none;
            pointer-events: none;
            transition:
                background-color 0.3s,
                border-color 0.3s,
                trnasform 0.6s,
                border-redius 0.3s,
                border 0.3s
            ;
        }
        .mouse__cursor.s1 {
            background-color: rgba(255, 186, 102, 0.856);
            border-color: orange;
        }
        .mouse__cursor.s2 {
            background-color: #7eb6ff;
            border-color: rgb(72, 37, 246);
            transform: scale(2) rotateY(720deg);
        }
        .mouse__cursor.s3 {
            background-color: #7ae163;
            border-color: rgb(234, 255, 208);
            transform: scale(1.5) rotateX(720deg);
        }
        .mouse__cursor.s4 {
            background-color: #6f6fff;
            border-color: rgb(54, 56, 119);
            transform: scale(10) rotateX(720deg);
            border-radius: 4px;
        }
        .mouse__cursor.s5 {
            background-color: #d1fffe;
            border-color: rgb(137, 141, 255);
            transform: scale(2) skew(40deg) rotateX(200deg);
            border-radius: 0;   
        }
        .mouse__cursor.s6 {
            background-color: #a3a3ff;
            border-color: rgb(107, 110, 190);
            transform: scale(3);
            border-radius: 0;
        }
        .mouse__text {
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        .mouse__text p {
            font-size: 2vw;
            line-height: 2;
        }
        .mouse__text p:last-child {
            font-size: 3vw;
        }
        .mouse__text p span {
            color: rgba(255, 186, 102, 0.856);
            border-bottom: 1px dashed rgba(255, 186, 102, 0.856);
        }
        .mouse__info {
            position: absolute;
            left: 0;
            bottom: 0;
            padding: 20px;
            font-size: 16px;
            line-height: 1.6;
        }
    </style>

마우스 이펙트 효과 주는 법

  • .mouse__cursor.s1 부터 .mouse__cursor.s6 까지 background-color를 설정합니다.
  • border-color와   trnasform,border-redius,border값을 이용해서 다양한 모양을 만들고 색을 입힐 수 있습니다.
  • transform에 scale은 크기를 나타내고 rotateX,Y 는 x축y축으로 회전하는 속도,skew는 기울기를 나타냅니다.
  • 이러한 효과들로 다양한 마우스 이펙트의 효과를 나타낼 수 있습니다.
  • 그리고 속성들이 추가될때는 반드시 mouse__cursor안에 transition에 속성들을 추가 해줘야 합니다.

 

완성된 마우스 이펙트 효과 01