Java script

[자바스크립트] javascript를 html에 import 하는 방법, fade in-out 애니메이션 만들기, setTimeout 함수 (+변수 선언 const, 선택자 queryselector, 버튼 onclick)

뉴라코 2024. 11. 26. 00:00

script 심어주기(java script를 html에 import하는 방법)

- 자바스크립트를 html에 import 할 때에는 body태그 또는 head태그에 해도 되지만

통상적으로 body태그 끝나는 지점에 하는 것을 추천 ex. <script src = "./js/start.js"> 

위에다가 입력했을 때, 자바 스크립트가 필요없는 첫 번째 화면부터 로딩이 뜰 것임. 

        <script src="./js/start.js"></script>
    </div>
</body>
</html>

 

  • const 변수를 상수로 선언(한 개만) / ver
  • queryselector는 문서에서 css선택자에 대응하는 것을 선택해준다.

// main변수= 문서 내 #main을 찾아서 가지고 와라
const main= document.querySelector("#main");
const qna= document.querySelector("#qna");

function begin(){
    main.style.display = "none";
    qna.style.display = "block";
}

onclick 사용하는 방법

html에서 on은 무엇을 기다릴 때 쓰는 것. 

따라서, 여기서 onclick은 기다리고 있다가 click되었을 때, javascript의 begin이라는 함수가 실행되어라!

  <button type="button" class="btn btn-danger mt-2" 
            onclick="js:begin()">시작하기</button>

 

버튼을 눌렀을 때 희미하게 다음 페이지로 넘어가는 애니메이션

https://www.tcpschool.com/css/css3_transform_animation

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com

 

 

- opacity는 투명도! opacity:0; 에서 opacity:1은 투명도가 점점 세진다는 뜻

아래는 위의 웹사이트에서 코드 복사해서 만든 fadeIn, fadeOut이 들어간 css

@keyframes fadeIn {
    from { opacity:0; }
    to { opacity:1; }
}

@keyframes fadeOut {
    from { opacity:1; }
    to { opacity:0; }
}

/* 크롬은 webkit */
@-webkit-keyframes fadeIn {
    from { opacity:0; }
    to { opacity:1; }
}

@-webkit-keyframes fadeOut {
    from { opacity:1; }
    to { opacity:0; }
}

 

start.js
// main변수= 문서 내 #main을 찾아서 가지고 와라
const main= document.querySelector("#main");
const qna= document.querySelector("#qna");

function begin(){
    main.style.WebkitAnimation = "fadeOut 1s ";
    main.style.Animation = "fadeOut 1s";
    qna.style.WebkitAnimation = "fadeIn 1s";
    qna.style.Animation = "fadeIn 1s";

setTimeout 사용하는 방법

:타이머가 만료된 뒤 함수나, 지정된 코드를 실행

 

https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout

 

Window: setTimeout() method - Web APIs | MDN

The setTimeout() method of the Window interface sets a timer which executes a function or specified piece of code once the timer expires.

developer.mozilla.org

start.js -setTimeout 사용

아래의 프로젝트에서는 function begin() 을 다 시행하고 display:none을 만들어 주기 위해 settimeout 사용

// main변수= 문서 내 #main을 찾아서 가지고 와라
const main= document.querySelector("#main");
const qna= document.querySelector("#qna");

function begin(){
    main.style.WebkitAnimation = "fadeOut 1s";
    main.style.Animation = "fadeOut 1s";
    setTimeout(() => {
        qna.style.WebkitAnimation = "fadeIn 1s";
        qna.style.Animation = "fadeIn 1s";
        setTimeout(() => {
            main.style.display = "none";
            qna.style.display = "block"
        }, 450);
    }, 450);
}

 

 

fadeIn, fadeOut - javascript setTimeout 활용