안녕하세요 오늘은 마우스 효과를 만들어보겠습니당 !

새로운 메서드와 속성들이 나왔으니 꼼꼼하게 정리해볼게요~

 

 

자바스크립트 마우스 이펙트(첫 번째) 만들기

css 세팅해주기

reset.css 설정

@import url('https://webfontworld.github.io/pretendard/Pretendard.css');
@import url('https://webfontworld.github.io/goodchoice/Jalnan.css');
@import url('https://webfontworld.github.io/sunn/SUIT.css');
@import url('https://webfontworld.github.io/gmarket/GmarketSans.css');
@import url('https://webfontworld.github.io/NexonLv1Gothic/NexonLv1Gothic.css');
@import url('https://webfontworld.github.io/PyeongChang/PyeongChang.css');
@import url('https://webfontworld.github.io/NexonMaplestory/NexonMaplestory.css');
@import url('https://webfontworld.github.io/vitro/VitroCore.css');
@import url('https://webfontworld.github.io/locus/LocusSangsang.css');
@import url('https://webfontworld.github.io/kohi/KOHIBaeum.css');

/* reset */
* {
    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: 'Pretendard';
    font-weight: 300;
}
.font02 {
    font-family: 'Jalnan';
    font-weight: 300;
}
.font03 {
    font-family: 'GmarketSans';
    font-weight: 300;
}
.font04 {
    font-family: 'SUIT';
    font-weight: 300;
}
.font05 {
    font-family: 'NexonLv1Gothic';
    font-weight: 300;
}
.font06 {
    font-family: 'PyeongChang';
    font-weight: 300;
}
.font07 {
    font-family: 'NexonMaplestory';
    font-weight: 300;
}
.font08 {
    font-family: 'VitroCore';
    font-weight: 300;
}
.font09 {
    font-family: 'LocusSangsang';
    font-weight: 300;
}
.font10 {
    font-family: 'KOHIBaeum';
    font-weight: 300;
}

mouse.css 설정

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;
    z-index: -1;
}
body.bg01::after {
    background-color: rgba(54, 71, 84, 0.6);
}
body.bg02::after {
    background-color: rgba(160, 102, 116, 0.7);
}
body.bg03::after {
    background-color: rgba(71, 51, 33, 0.7);
}
body.bg04::after {
    background-color: rgba(66, 80, 69, 0.7);
}
body.bg05::after {
    background-color: rgba(104, 78, 88, 0.7);
}
body.bg06::after {
    background-color: rgba(83, 80, 66, 0.7);
}
body.bg07::after {
    background-color: rgba(65, 39, 88, 0.7);
}
body.bg08::after {
    background-color: rgba(30, 53, 49, 0.7);
}
body.bg09::after {
    background-color: rgba(49, 53, 54, 0.7);
}
body.bg10::after {
    background-color: rgba(38, 16, 41, 0.7);
}

/* header */
#header {
    padding: 20px;
    position: absolute;
    left: 0;
    top: 0;
}
#header h1 {
    margin-bottom: 10px;
}
#header p {
    margin-bottom: 10px;
}
#header a {
    color: #fff;
}
#header li {
    display: inline-block;
}
#header li a {
    display: inline-block;
    text-align: center;
    line-height: 1.8;
    border: 1px solid #fff;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    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;
}

reset.css와 mouse.css에 이미지와 폰트를 설정해줍니다.

앞으로 쓰고싶은 이미지와 폰트는 class로 지정해주었기 때문에 뒤에 이름을 붙여 불러와주면 됩니다!  

구조 짜기

<body class="img01 bg01 font09">
    <header id="header">
        <h1>Javascript Mouse Effect01</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="mouse__wrap">
            <div class="mouse__cursor"></div>
            <div class="mouse__text">
                <p>All you need in this life is <span class="s1">ignorance</span> and <span class="s2">confidence</span>, then <span class="s3">success</span> is sure. </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:dsy1943@naver.com">dsy1943@naver.com</a>
    </footer>
    <!-- //footer -->

이번엔 배경에 사진을 넣고, 그 위에 명언(한국어, 영어)을 써서 그 위로 마우스 효과를 주겠습니다.

또한 좌표값을 화면에 띄워주기 위헤 ul태그와 li태그를 사용해 내용들을 적어줍니다.

중간에 좌표값을 스크립트 부분으로 처리해주기 위해 span처리를 해줍니다.

 

마우스 커서에 따른 좌표값 스크립트 짜기

<script>
        window.addEventListener("mousemove", function(event){
            document.querySelector(".clientX").innerHTML = event.clientX;
            document.querySelector(".clientY").innerHTML = event.clientY;
            document.querySelector(".offsetX").innerHTML = event.offsetX;
            document.querySelector(".offsetY").innerHTML = event.offsetY;
            document.querySelector(".pageX").innerHTML = event.pageX;
            document.querySelector(".pageY").innerHTML = event.pageY;
            document.querySelector(".screenX").innerHTML = event.screenX;
            document.querySelector(".screenY").innerHTML = event.screenY;
        });
</script>

window.addEventListner를 통해 마우스가 움직였을 때 이벤트 함수가 적용시키도록 해줍니다.

.clientX값부터 screenY값까지 innerHTML을 써서 좌표값이 출력될 수 있게 해줍니다.

 

window.addEventListner?

DOM 이벤트를 처리하기 위한 메소드 중 하나입니다. 이 메소드를 사용하면 특정 이벤트(예: 클릭, 마우스 이동, 키보드 입력 등)가 발생할 때 실행할 함수를 등록할 수 있습니다.

마우스 커서 스크립트

// 선택자
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";
});

변수를 설정해 마우스 커서가 움직일 때, 함수를 실행시키도록 해줍니다.

여기서 - 25를 한 이유는 마우스의 원이 중앙으로 오도록 설정해준 것입니다. 

 

이제 span처리를 한 부분마다 각자 다른 애니메이션 효과를 주기 위해 span에 이름을 붙여주겠습니다.

<div class="mouse__text">
    <p>All you need in this life is <span class="s1">ignorance</span> and <span class="s2">confidence</span>, then <span class="s3">success</span> is sure. </p>
    <p>삶에 필요한 것은 <span class="s4">무지</span><span class="s5">자신감</span>이다. 그렇다면 <span class="s6">성공</span>은 확실하다.</p>
</div>

span class="s1" ~ span class="s6"까지 총 6개의 span을 만들어 강조할 부분을 강조해주었습니다.

 

기존 방식으로 스크립트 짜기

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");
});

document.querySelector().로 선택한 뒤, addEventListener를 통해 마우스를 위에 오버했을 때 효과가 나도록 함수를 실행시킵니다. 또, 반대로 마우스를 아웃했을 때 효과가 제거되는 스크립트도 짜줍니다.

 

이걸 확인해보려면 css를 통해 애니메이션을 줘야겠죠?

 

CSS로 애니메이션 설정해주기

.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(255, 255, 255, 0.1);
    user-select: none;
    pointer-events: none;
    transition: 
        background-color 0.3s,
        border-color 0.3s,
        transform 0.6s
    ;
}
.mouse__cursor.s1 {
    background-color: rgba(212, 112, 112, 0.4);
    border-color: rgb(255, 112, 112);
}
.mouse__cursor.s2 {
    background-color: rgba(238, 131, 59, 0.4);
    border-color: #ff9257;
    transform: scale(2) rotateY(360deg);
}
.mouse__cursor.s3 {
    background-color: rgba(255, 240, 80, 0.4);
    border-color: #ffd23f;
    transform: scale(1.5) rotateX(540deg);
}
.mouse__cursor.s4 {
    background-color: rgba(79, 255, 59, 0.4);
    border-color: #8dff64;
    transform: scale(10);
    border-radius: 1px;
}
.mouse__cursor.s5 {
    background-color: rgba(78, 134, 255, 0.4);
    border-color: #7371fe;
    transform: scale(5) skew(140deg) rotate(200deg);
}
.mouse__cursor.s6 {
    background-color: rgba(186, 96, 255, 0.4);
    border-color: #f175ff;
    transform: scale(0.1);
}
.mouse__text {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
.mouse__text p {
    font-size: 2vw;
    line-height: 1.9;
}
.mouse__text p:last-child {
    font-size: 3vw;
}
.mouse__text p span {
    color: #C886A2;
    border-bottom: 1px solid #C886A2;
}
.mouse__info {
    position: absolute;
    left: 0;
    bottom: 0;
    padding: 20px;
    font-size: 16px;
    line-height: 1.6;
}

이렇게 각각  s1 ~ s6까지 각각 다른 애니메이션 효과를 부여해줍니다.

 

하지만 이렇게 하나하나씩 다 스크립트를 짜주면 소스가 많아지고, 복잡해지고 지저분해지겠죠?

이걸 for문으로 바꿔보겠습니다.

 

for문 사용

// 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문을 사용해 i값을 지정해주고, (총 6개) 메서드 안에 들어가는 값을 그냥 i라고 적으시면 안됩니다!

s1~ s6이니 문자열을 써주고 ".s" + i를 해주셔야 위처럼 동일하게 나옵니다.

 

forEach() 사용

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));
    });
});

이번엔 forEach로 바꿔 스크립트를 짜줍니다. forEach 앞에 선택자를 이용해 선택해줍니다. 이때, .mouse__text span을 선택해주고, 요소값 안에는 span과 num을 넣어주었습니다.

 

num은 0부터 시작하는게 아닌 1부터 시작해야하므로 +1을 해줍니다.

 

getAttribute();

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

이번엔 새로운 메서드를 써서 스크립트를 짜보았습니다.

 

일단 getAttribute가 무엇인지 알아봐야겠죠?

 

 getAttribute?

getAttribute는 JavaScript에서 DOM (Document Object Model) 요소의 속성 값을 가져오는 메서드입니다.

 

attr 변수를 지정해주고 그 안에 getAttribute를 사용해 속성 값을 가져와줍니다. 

즉, attr에는 s1 ~ s6까지 들어있어요!

 

완성된 페이지/코드 보기

 

https://github.com/YeoDaSeul4355/web2023/blob/main/javascirpt/mouse/mouseEffect01.html

728x90
반응형
다쭐◠‿◠