마우스오버 이벤트가 특정 영역 안에서만 이루어졌으면 좋겠습니다.
330
작성한 질문수 6
마우스가 그림 위에 오버되면 원을 생성하는 인터랙티브 기능을 구현했습니다.
사진 안에서만 원들이 생성 되고 사진 영역을 벗어나면 원이 그려지지 않았으면 좋겠는데 어떻게 해야할까요?
<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 인턴입니다.
님의 코드에서는 마우스 오버 이벤트로 원을 생성하는 기능이 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.left와 circle.style.top에서 원의 생성 위치를 조정하여 leaf 요소의 경계 내에서만 원이 생성되도록 계산해야 할 수도 있습니다. e.pageX - leaf.offsetLeft 및 e.pageY - leaf.offsetTop는 마우스 위치에서 leaf 요소의 위치를 빼서 원이 leaf 내부에 정확히 위치하도록 보정합니다.
수강자료 다운로드 관련 문의
0
23
2
선택정렬 이해하기 & 구현하기
0
10
1
mission12-01 guide.md파일 누락
0
15
1
자료집 관련
0
25
2
13. (App 2) 기본기 훈련 에서
0
35
1
챌린지 시작일 문의
0
40
0
2. 어떤 도구를 사용하는 것이 가장 유리할까? 강의 중
0
32
1
11차시 Antigravity IDE 설치 후
0
34
1
처음 에이전트 설정을 잘못 했을 경우 수정 하는 방법
0
36
1
5,6,7,8 내용이 없어요
0
33
1
ThemeProvider를 이용해서 NextThemeProvider를 따로 생성하여 Layout.tsx에 적용하는 이유는 뭘까요?
0
31
1
mission 09-01 을 수행할 수 없어요
0
33
1
Context API vs Zustand 그리고 Auth
0
39
2
순수 함수 / 순수 컴포넌트
0
29
1
css box-sizing 관련 질문
0
36
2
스니펫이 이상해요
0
34
2
Editor Component의 최적화 불가능 이슈
0
40
2
useCallback ⊂ useMemo
0
38
2
깃허브 저장소를 어디에 첨부하셨나요?
1
46
1
nestjs 강의는 없나요??
1
42
2
스타터 저장소
1
47
1
What is Rxjs
0
34
1
라이브러리 설치 질문
0
35
2
linter 질문
0
42
2





