inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

312

ㄴㄹㅇㄹㄴㄹㅇ

작성한 질문수 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 내부에 정확히 위치하도록 보정합니다.

몽고 db 접속 오류

0

18

1

3강 질문

0

29

2

74. 데이터 캐시 - 1 (이론) 강의 영상 누락

0

35

1

2강 nodejs 3단계 설명 질문

0

40

1

imagesLoaded에 관한 질문

0

19

2

useEffect와 lifecycle문의

0

30

2

프론트엔드 학습 수준 문의

0

42

2

리액트 챕터별 코드에서 eslint 설정파일이 없어요

0

51

2

최근 코테, 과제 테스트 트렌드

0

71

2

lucide react 아이콘 설치

0

48

2

17강 zustand store 서버에서 생성

1

42

1

문의관련 문의

0

45

2

next.js 를 2대이상 실행하는 경우 제공하는 cache 기능들은 어떻게 되나요?

0

61

2

76. 전문성 더하기: 놓치면 아쉬운 관련 기술들 수업 자료가 없어요.

0

50

2

ai 도구 질문

0

35

1

저는 왜 콘솔에서 props가 한 줄만 찍히나요?

0

48

1

렌더링 차단 리소스 javascript 실행에 관련해서 질문 있습니다.

0

50

2

데이터 로딩중 화면만 계속 나와요!!

0

56

2

퍼블리셔일경우 어느정도 수준까지 강의를 들어야할까요

0

80

2

02-04 layout.tsx 구조가 달라요

0

62

2

불변성을 지키며 수정 삭제를 할때도 Map이 유리한가요?

0

56

1

개인 프로젝트로 앱 개발해서 다운로드 1300 달성했는데 어느 정도 의미가 있을까요? (안드로이드 개발자)

0

72

1

22강 강의 영상 문의 드립니다.

0

52

2

20강 마무리작업에서

0

38

2