[WEB]JS, Funtion 만들기-동적 UI 만들기

JS, Funtion 만들기-동적 UI 만들기

 

동적 UI 란?

블로그가 있을 때 새로운 글을 올리기 위해서

추가 버튼을 눌러서 글을 작성하고완료버튼을 눌렀을 때

없었던 글 목록이 생기는 기능과 같다고 생각하면 된다

이미 만들어져 있는 것이 아닌 없었는데 동작을 통해서 새로 생기는 것을 동적생성 이라고도 부른다

 

etc-image-0

추가 버튼을 누르면 메세지 박스가 생성되는 버튼을 js를 사용해서 만들기 위해서 

다음과 같이 HTML/CSS 디자인을 먼저 해준다

 

더보기
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>javascript</title>
    <link href="css.css" rel="stylesheet" />
  </head>
  <body>
    <div class="alert-box-bg">
      <div div class="alert-box">hello!</div>
      <button onclick="close-btn-js">close</button>
    </div>
    <button class="plus-btn">추가</button>
  </body>
</html>
body {
  margin: 10;
}
div {
  box-sizing: border-box;
}
.alert-box-bg {
  background-color: tan;
  padding: 20px;
  border-radius: 5px;
  display: flex;
}
.alert-box {
  padding-right: 10px;
}

 

추가 버튼을 누르면 메세지 박스가 보여주게 하기 위해서

display :none 을 사용해서 추가를 누르기 전에는 박스가 보이지 않도록 해준다

etc-image-1

body {
  margin: 10;
}
div {
  box-sizing: border-box;
}
.alert-box-bg {
  background-color: tan;
  padding: 20px;
  border-radius: 5px;
  display: flex;
  display: none;
}
.alert-box {
  padding-right: 10px;
}

 

추가 버튼을 눌렀을 때 숨겨 두었던 메세지 박스를 보여주어야 하기 때문에

button 이벤트를 받기 위해서 onClick="이벤트" 를 태그 속성 안에 추가 해주어야한다

Close 버튼을 누르면 메세지 박스가 사라져야하고 Add 버튼을 누르면 메세지 박스가 보여야 한다

 

 

document.getElementById('box').style.display ='none';
document.getElementById('box').style.display='block';

 

즉, display :none 을 사용해서 보여지지 않게 했던 부분을 display:block 이 되게 해서 

보이지 않았던 부분이 보이도록 해주면 된다.

 

 <body>
 <div class="alert-box-bg" id="box">
      <div div class="alert-box">hello!</div>
      <button onclick="document.getElementById('box').style.display ='none';">
        Close
      </button>
    </div>
    <button onclick="document.getElementById('box').style.display='block';">
      Add
    </button>
 </body>

 

javascript 파일에서 함수 불러오기

 

<head>태그 안에 생성한.js 파일을 넣어준다

    <script src="js.js"></script>

button을 열고 닫는데 작성된 코드를 .js 파일안에 함수로 만들어 준다

function box_close() {
  document.getElementById("box").style.display = "none";
}
function box_open() {
  document.getElementById("box").style.display = "block";
}
 <body>
    <div class="alert-box-bg" id="box">
      <div div class="alert-box">hello!</div>
      <button onclick="box_close()">Close</button>
    </div>
    <button onclick="box_open()">Add</button>
    <script></script>
  </body>

그리고 만들어진 함수를 button onclick()이벤트 안에 적용해주면 위와 같은 똑같은 기능을 한다

button.gif