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

24.05.07 17:40 작성 조회수 32

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

 

 

답변 1

답변을 작성해보세요.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2024.05.08

안녕하세요, 인프런 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 내부에 정확히 위치하도록 보정합니다.