마우스오버 이벤트가 특정 영역 안에서만 이루어졌으면 좋겠습니다.
337
작성한 질문수 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 내부에 정확히 위치하도록 보정합니다.
Part2 수강 방법
0
19
1
20강 4분 30초 코드와 6분 30초 코드 관련 질문
0
17
0
영상에서 소개되는 코드와 강의 노트 코드가 달라요
0
27
1
오디오 문제
0
48
2
TTL 산정 기준
0
42
1
10월 15일 삭제예정 강의 문의
0
58
1
강의제목에 10/15일 삭제라고 나와있는데,
0
63
1
스크립트 영상 미일치
0
101
3
감정일기장 다이어리 필터 적용할때 컨텍스트를 Home에서 가져오는 특별한 이유가 궁금합니다.
0
68
2
강의 설명 중에 헷갈리는 것이 있네요
0
79
2
수업자료 관련 문의
0
88
3
1강 동영상 재생 오류
1
78
2
Composition단계에서 `Layer`는 누가 만드는지
0
54
1
Strict Mode 예시 질문!
0
71
2
수업이 안보여요
0
72
1
저자 블로그에 있는 강의는 어떤 강의인가요?
1
73
1
[해결됨]윈도우즈 환경에서 타입 스크립트 파일이 실행이 안됩니다.
1
97
5
4강 카드뉴스 자동화 자료가 안보입니다!!
0
120
2
윈도우즈 환경에서 진행중입니다.
0
73
2
4강 카드뉴스 자동화 자료
6
134
1
라이브 강의 영상 녹화본이 있을까요?
0
109
1
인증이 늦었습니다ㅜㅜ 확인부탁드립니다
0
100
1
스웨거 접속이 안되는데 확인 부탁드립니다.
0
68
1
설명이 잘못된거같습니다.
1
85
2





