inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

마우스오버 이벤트가 특정 영역 안에서만 이루어졌으면 좋겠습니다.

317

ㄴㄹㅇㄹㄴㄹㅇ

작성한 질문수 6

0

스크린샷 2024-05-07 오후 5.35.41.png마우스가 그림 위에 오버되면 원을 생성하는 인터랙티브 기능을 구현했습니다.

사진 안에서만 원들이 생성 되고 사진 영역을 벗어나면 원이 그려지지 않았으면 좋겠는데 어떻게 해야할까요?

 

<div id="leaf">
</div>
<body>
  <script>
        let leaf = document.getElementById("leaf");
        let jean = document.getElementById("jean");
        
        leaf.addEventListener("mouseover",onmouseover);
        //window.addEventListener("mouseover",onmouseover);

        function onmouseover(e){
            let circle = document.createElement("div");
            let radius = Math.floor(Math.random()* 150+50);
            let randomBrightColor = () => {
  let color_r = Math.floor(Math.random() * 127 + 128).toString(16);
  let color_g = Math.floor(Math.random() * 127 + 128).toString(16);
  let color_b = Math.floor(Math.random() * 127 + 128).toString(16);
  return `#${color_r+color_g+color_b}`;
}
            circle.style.position = "absolute",
            circle.style.opacity = Math.random()*0.9 + 0.1;
            circle.style.width = radius+"px";
            circle.style.height = radius+"px";
            circle.style.borderRadius = "50%"
            circle.style.backgroundColor =  randomBrightColor();
            circle.style.left= e.pageX -radius * 0.5 + "px";
            circle.style.top= e.pageY -radius * 0.5 + "px";
            circle.style.transform= "scale(0,0)";
            gsap.to(circle, {scale:1 , ease: "back.out(1.7)", duration: 0.3})
            document.body.appendChild(circle);
                circle.style.zIndex = "1";
        }

    </script>
</body>

css 는 다음과 같습니다

#leaf{
    width: 600px;
    height: 600px;
    overflow: hidden;
    background-image: url(https://images.unsplash.com/photo-1714571883639-fe73d73ef8a9?q=80&w=3387&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D);
}

 

 

javascript

답변 1

0

인프런 AI 인턴

안녕하세요, 인프런 AI 인턴입니다.

님의 코드에서는 마우스 오버 이벤트로 원을 생성하는 기능이 window 또는 document.body를 대상으로 설정되어 있어 사진 영역 밖에서도 원이 생성됩니다. 원이 사진 안에서만 생성되게 하려면, 이벤트 리스너를 leaf에만 적용해야 합니다. 님께서 이미 leaf.addEventListener("mouseover",onmouseover);를 사용하여 leaf 요소에 이벤트 리스너를 추가하신 부분이 올바른 접근입니다. 다만, 문제는 생성된 원을 leaf 요소 안에 추가하는 것입니다.

현재 코드에서는 document.body.appendChild(circle);을 통해 원을 body에 추가하고 있습니다. 이를 leaf에 추가하여 원이 leaf 영역 안에서만 나타나도록 수정해야 합니다. 따라서, document.body.appendChild(circle); 대신에 leaf.appendChild(circle);를 사용하면 됩니다. 이렇게 하면 원이 leaf 요소의 자식 요소로 추가되어, leaf의 범위를 벗어날 수 없게 됩니다.

아래는 수정된 script 부분입니다:

<script>
    let leaf = document.getElementById("leaf");

    leaf.addEventListener("mouseover", onmouseover);

    function onmouseover(e) {
        let circle = document.createElement("div");
        let radius = Math.floor(Math.random() * 150 + 50);
        let randomBrightColor = () => {
            let color_r = Math.floor(Math.random() * 127 + 128).toString(16);
            let color_g = Math.floor(Math.random() * 127 + 128).toString(16);
            let color_b = Math.floor(Math.random() * 127 + 128).toString(16);
            return `#${color_r+color_g+color_b}`;
        }
        circle.style.position = "absolute";
        circle.style.opacity = Math.random() * 0.9 + 0.1;
        circle.style.width = radius + "px";
        circle.style.height = radius + "px";
        circle.style.borderRadius = "50%";
        circle.style.backgroundColor = randomBrightColor();
        circle.style.left = e.pageX - leaf.offsetLeft - radius * 0.5 + "px"; // 수정된 부분
        circle.style.top = e.pageY - leaf.offsetTop - radius * 0.5 + "px"; // 수정된 부분
        circle.style.transform = "scale(0,0)";
        gsap.to(circle, { scale:1, ease: "back.out(1.7)", duration: 0.3 });
        leaf.appendChild(circle); // 수정된 부분
        circle.style.zIndex = "1";
    }
</script>

circle.style.leftcircle.style.top에서 원의 생성 위치를 조정하여 leaf 요소의 경계 내에서만 원이 생성되도록 계산해야 할 수도 있습니다. e.pageX - leaf.offsetLefte.pageY - leaf.offsetTop는 마우스 위치에서 leaf 요소의 위치를 빼서 원이 leaf 내부에 정확히 위치하도록 보정합니다.

[46강] EventEmitter를 활용한 10가지 패턴 중 플러그인 아키텍처

0

12

2

강의가 누락된것 같습니다.

0

32

2

용어 발음법이 계속 바뀌는 것 같은데 이런 부분들 개선이 가능할까요...?

0

41

1

counter01.html은 어디있을까요?

1

16

1

존재하지 않는 일기 url입력 시 alert이 두 번 떠요

0

34

1

useState 직접 구현 부분에서 질문이 있습니다.

1

42

1

학습을 하고 블로그에 정리를 해도 괜찮을까요?

1

41

1

교재(3쇄)와 강의 내용 문의

0

35

2

섹션2번 부분 강의 화면이 잘 못된것 같아서 문의합니다.

0

23

1

call stack 표현이 잘못표현된것이 아닌가요?

0

79

2

React 와 Virtual DOM 의 이야기 영상 실행이 안됩니다.

0

35

1

일반 강의와 차이점?

1

57

1

!= 연산자의 역할

0

35

1

중요하진 않지만 설명하신부분에서 안된부분..

1

39

1

강의 듣는 순서가 어떻게 되나요?

0

53

1

stopPropagation()에 대해서 질문 있습니다.

0

52

2

12.13) 하단 여백 스타일링 관련 질문 드립니다.

0

67

2

27강 Context내 RSC 사용 관련 문의

0

88

3

혹시 다음 강의 제작 예정된 것들이 있을까요?

0

94

1

Enable Linting 항목을 찾을수가 없습니다.

0

48

2

에러 질문드립니다

0

64

2

1강 질문

0

73

2

윈도우에서는동작줄이기가어디에있을까요??

0

39

1

백오피스를 개발할 때 아키텍처 구성에 대한 질문

0

63

3