• 카테고리

    질문 & 답변
  • 세부 분야

    웹 개발

  • 해결 여부

    미해결

질문 있습니다~

23.07.27 14:43 작성 조회수 116

0

안녕하세요 선생님:-)

강의 끝 부분에 특정 번호를 넣으면

그 번호의 문이 열리게 activate 함수를

수정해보라고 하셔서 코딩을 해봤는데

이 방법처럼 해도 되는지 잘 모르겠어서요~

이렇게 해도 되나요?

 

<script>
        (function(){
            const stageElem = document.querySelector('.stage');
            let currentItem;

            //활성화
            function activate(elem){
                if(typeof(elem) == "number"){
                    activate(document.querySelector('.door:nth-child('+ elem +')'));
                    return;
                }
                    elem.classList.add('door-opened');
                    currentItem = elem;
            }

            //비활성화
            function inactivate(elem){
                elem.classList.remove('door-opened');
            }

            function doorHandler(e){
                const targetElem = e.target;
                
                //비활성화
                if(currentItem){
                    inactivate(currentItem);
                }

                //활성화
                if(targetElem.classList.contains('door-body')){
                    activate(targetElem.parentNode);
                }
            }
            stageElem.addEventListener('click', doorHandler);
            activate(3);
        })();
    </script>

 

답변 2

·

답변을 작성해보세요.

0

AI 인턴의 답변처럼, activate 안에서 activate를 호출하고 있어서 그 부분을 수정하는게 좋을 것 같아요~
아래 코드를 작성해 보았습니다. currentItem 대신, currentItemNumber라는 변수에 숫자를 넣어두고, 계속 그 숫자를 이용하는 식으로 코딩했어요.
수업 노트에도 넣어두어야겠습니다^^

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Interactive Web</title>
	<link rel="stylesheet" href="css/reset.css">
	<style>
		.stage {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100vw;
			height: 100vh;
			background: #333;
		}
		.door {
			position: relative;
			width: 100px;
			height: 150px;
		}
		.door-back {
			overflow: hidden;
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background: black;
		}
		.ilbuni {
			position: absolute;
			left: 0;
			bottom: 0;
			width: 100px;
			height: 100px;
			background-repeat: no-repeat;
			background-position: 50% 100%;
			background-size: contain;
			transform: translate3d(100%, 0, 0);
			transition: 0.5s 0.5s;
		}
		.door:nth-child(1) .ilbuni { background-image: url(images/ilbuni_0.png); }
		.door:nth-child(2) .ilbuni { background-image: url(images/ilbuni_1.png); }
		.door:nth-child(3) .ilbuni { background-image: url(images/ilbuni_2.png); }
		.door-body {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			transition: 0.5s;
			transform-origin: 0%;
			cursor: pointer;
		}
		.door:nth-child(1) .door-body { background: rgba(255, 0, 0, 0.7); }
		.door:nth-child(2) .door-body { background: rgba(0, 255, 0, 0.7); }
		.door:nth-child(3) .door-body { background: rgba(0, 0, 255, 0.7); }
		.door-opened .door-body {
			transform: perspective(800px) rotateY(-110deg);
		}
		.door-opened .ilbuni {
			transform: translate3d(0, 0, 0);
		}
	</style>
</head>
<body>
	<div class="stage">
		<div class="door">
			<div class="door-back">
				<div class="ilbuni"></div>
			</div>
			<div class="door-body"></div>
		</div>
		<div class="door">
			<div class="door-back">
				<div class="ilbuni"></div>
			</div>
			<div class="door-body"></div>
		</div>
		<div class="door">
			<div class="door-back">
				<div class="ilbuni"></div>
			</div>
			<div class="door-body"></div>
		</div>
	</div>

	<script>
		(function() {
			const stageElem = document.querySelector('.stage');
			// 현재 활성화된 아이템의 번호를 저장
			let currentItemNumber;

      // 각 문에 data-number를 세팅(0, 1, 2)
      const doors = document.querySelectorAll('.door');
      doors.forEach((door, index) => {
        door.dataset.number = index;
      });

			// 활성화
			function activate(number) {
        const elem = document.querySelector(`.door[data-number="${number}"]`);
				elem.classList.add('door-opened');
				currentItemNumber = number;
			}

			// 비활성화
			function inactivate(number) {
        const elem = document.querySelector(`.door[data-number="${number}"]`);
				elem.classList.remove('door-opened');
			}

			function doorHandler(e) {
				const targetElem = e.target;

				if (currentItemNumber >= 0) {
					inactivate(currentItemNumber);
				}

				if (targetElem.classList.contains('door-body')) {
					activate(targetElem.parentNode.dataset.number);
				}
			}

			stageElem.addEventListener('click', doorHandler);

      activate(1);
		})();
	</script>
</body>
</html>

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.07.29

안녕하세요, 인프런 AI 인턴이에요. 제가 보았을 때는 해당 코드로도 문제가 없어 보입니다. 코드의 동작을 정확히 이해하고 구현하셨다면, 해당 코드로 특정 번호의 문이 열리는 기능을 구현하실 수 있을 것 같아요. 그런데 activate 함수 내에서 다시 activate 함수를 호출하는 부분이 보이는데, 이 부분을 재귀 호출로 사용하실 것 같은데, 재귀 호출은 사용 조건이 명확하지 않으면 무한 반복되는 상황이 발생할 수 있어요. 그래서 재귀 호출을 사용하실 때는 종료 조건을 정확히 설정해주셔야 합니다. 현재 코드에서는 종료 조건이 없어 조심해야 할 것 같아요. 그 외에는 문제가 보이지 않습니다. 번호를 넣어서 코드를 실행해보시고, 원하는 기능이 잘 작동하는지 확인해보세요. 계속해서 도움이 필요하시면 언제든지 물어보세요!