Javascript 이미지 랜덤 출력하기

toastedEevee·2022년 9월 5일
0

노마드코더에서 바닐라JS 강의를 듣다가 배경이미지를 랜덤으로 변경하는 부분을 보고 내 블로그 홈버튼에도 적용을 해보았다.

강의 코드 ⬇️⬇️

<script>
	const images = ["0.jpeg", "1.jpeg", "2.jpeg"];

	const chosenImage = images[Math.floor(Math.random() * images.length)];

	const bgImages = document.createElement("img");
	bgImages.src = `img/${chosenImage}`;
    
    document.body.appendChild(bgImage);
</script>

랜덤으로 변경되는 이미지를 chosenImage 변수로 받고,
createElement로 img 요소를 생성한 후, src 속성으로 랜덤이미지의 경로도 생성해준다.

createElement()

지정된 태그에 대한 요소의 인스턴스를 만든다.

  • argument: (tagName: keyofHTMLElementTagNameMap, options?: ElementsCreationNameMap)

💡String과 변수를 작성할 때 백틱(``) 안에 작성하면 ""와 연결연산자를 사용할 필요 없이 한 번에 작성할 수 있다!

마지막으로 appendChild를 써서 body 안에 img 요소를 자식 태그로 붙이면 배경으로 이미지가 랜덤하게 출력되는 방식이다.

appendChild()

하위에 자식 요소로 추가한다.

<script>
document.body.appendChild(bgImage);
</script>

내 블로그의 홈버튼에 적용하기 위해서는 이미지의 width 속성을 지정해야 하고, body 안에 자식 태그로 들어가는 게 아닌, 이미 자리가 지정된 a 태그 사이에 집어 넣어야 함!!

어떻게 하지...? 🧐

.
.
.
.
.
.
.
.
.
.

내가 적용한 코드 ⬇️⬇️

<script>
	const images = ["1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png", "8.png", "9.png"];

	const chosenImg = images[Math.floor(Math.random() * images.length)];

	const btnImg = document.createElement("img");
	btnImg.src = `img/home-btn/${chosenImg}`;
	btnImg.width = 120;
	btnImg.alt = "main-logo";

	const homeBtn = document.querySelector(".btn-enter")
	homeBtn.insertAdjacentElement("afterbegin", btnImg);
</script>

querySelector 메소드로 class 선택자가 블라블라인 요소를 가져와서 변수로 받고,
insertAdjacentElement 메소드를 사용해서 원하는 위치에 원하는 요소 노드를 삽입하면 된다.

insertAdjacentElement()

호출된 요소에 주어진 상대적인 위치에 지정한 요소 노드를 삽입한다.
The insertAdjacentElement() method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.

  • argument: (Position, Element node)

삽입 위치는?
"beforebegin" | "afterbegin" | "beforeend" | "afterend"
"요소 앞에"| "요소 안의 첫 자식" | "마지막 자식" | "요소 뒤에"

.
.
.
.
.
.
.
.
.
.
.
.
.

짜잔! 이렇게 완성된 토이 스토리 뤤덤 벝흔 시리즈

profile
내가그린솜뭉치

0개의 댓글