📌Language/JavaScript

javascript로 html body 요소 찾기, 추가하기 // js에서 linear-gradient 사용하기

hellohailie 2022. 4. 21. 23:09
반응형

오늘은 javascript로 html 안에 있는 body 요소를 찾고 추가하는 방법에 대한 포스팅입니다. 

 

나의 목표!

 html에 있는 버튼을 누르면 js에 쓴 함수인 function 실행하고 이걸 html에 넣기!

 

 

1. html 요소를 가져오자.

나는 html - body - button을 가져올겁니다. 

 

const button = document.querySelector("button"); // html의 button을 불러오고, 이걸 js에서 button이라고 부를거야!
const body = document.querySelector("body"); // html의 body을 불러오고, 이걸 js에서 body라고 부를거야!

 

 

2. js에 button을 누르면 기능이 나타나게 하자.

button.addEventListener("click",function colorChange () { //button에 addEventListener를 실행해서 클릭하면 function이 실행되게 한다. 
    const chosenRandomColor1 = colors[(Math.floor(Math.random() * colors.length))];  // 여기서 나는 랜덤인 상수를 써서 이런 식을 가져왔다. 
    const chosenRandomColor2 = colors[(Math.floor(Math.random() * colors.length))];  // 여기서 나는 랜덤인 상수를 써서 이런 식을 가져왔다. 
    body.style.backgroundImage =`linear-gradient(to right, ${chosenRandomColor1}, ${chosenRandomColor2})`;
})   // html의 body 안에 style을 만들고 거기에 backgroundImage를 넣어줘. 근데 linear-gradient함수를 사용해줘.

 

 

 

반응형