상세 컨텐츠

본문 제목

[JS]Quotes and Background_Math.random(), createElement()

Java Script

by (방울)도마토 2023. 10. 18. 14:49

본문

1. Math - 수학에서 자주 사용하는 상수와 함수들을 미리 구현해 놓은 내장 객체(함수 객체 X)

  • Math.random() : 난수 생성
    • float로 반환함
    • Math.randon() * 10 → 0 에서 10 사이 (10 포함 X)의 난수 생성

- int 부분만 가져오는 3가지 방법 

1) round() : 반올림

2) ceil() : 올림 

3) floor() : 내림

 

// in HTML
     <div id="quote">
        <span></span>
        <span></span>
    </div>


// ==========================================================================================
const quotes = [
    {
        quote: "The greatest glory in living lies not in never falling, but in rising every time we fall.",
        author: "Nelson Mandela"
    },
	...
]


const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");

const todaysQuote = quotes[Math.floor(Math.random()* quotes.length)];
	// array 길이에 따라 random한 수 생성

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;

 

 

2. js에서 만든 요소 → html에 옮기기 

 

* document.createElement() : 지정한 tagName의 HTML 요소를 만들어 반환 

<추가>

  • appendChild() 
  • insertBefore()

<삭제> 

  • removeChild()
  • replaceChild()
const images = ["0.jpeg", "1.jpeg", "2.jpeg"];

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

const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImage}`;
	// HTML에 전달할 요소 생성 (<img src="">)

console.log(bgImage);

document.body.appendChild(bgImage);
	// HTML에 요소 추가하기

'Java Script' 카테고리의 다른 글

[JS] Clock  (0) 2023.10.18
[JS]03. Login 2  (1) 2023.10.10
[JS]03. Login 1  (0) 2023.10.10
[JS]02. JavaScript on the Browser 3  (0) 2023.10.07
[JS]02. JavaScript on the Browser 2  (0) 2023.10.07

관련글 더보기

댓글 영역