영벨롭 개발 일지

[JavaScript]자바스크립트로 input 박스 제어 본문

Programming Language/JavaScript

[JavaScript]자바스크립트로 input 박스 제어

영벨롭 2022. 4. 19. 15:55

[ HTML 코드 ]

 

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  
  <!--google material icon 사용
  class="material-icons"-->
  <link rel="stylesheet" href="http://fonts.googleapis.com/icon?family=Material+Icons">

  <!-- main.css 연결 -->
  <link rel="stylesheet" href="./css/main.css">
  <!-- main.js 연결 -->
  <script defer src="./js/main.js"></script>
</head>
<body>

  <div class="input-box">

    <input type="text" />

    <div class="material-icons">search</div>
    
  </div>
  
</body>
</html>

 

 

 

 

[ 스타일 적용 ]

 

.input-box {
  margin: 10px;
  height: 35px;
  position: relative; /* 아이콘 위치 기준 */
}

.input-box input {
  width: 35px;
  height: 35px;
  padding: 4px 10px;
  border: 2px solid black;
  box-sizing: border-box;
  border-radius: 5px;
  outline: none;
  color: #777;
  transition: width .5s;
}

.input-box input:focus {
  /* 포커스 되면 가로 너비와, 테두리 선 색상 변경 */
  width: 200px;
  border-color: blue;
}

.input-box .material-icons {
  height: 24px; /* google material icons 기본 크기: 24px */
  position: absolute; /* input 창 위에 오도록*/
  top: 0;
  bottom: 0;
  left: 5px;
  margin: auto;
  transition: .5s;
}

 

 input 창을 클릭하게 되면 다음과 같이 변합니다. 

 

 

 이때 문제점이 정확히 input 창을 클릭해야지만 변화하고, 돋보기 아이콘을 누르면 변화하지 않습니다. 

 

 이제 자바스크립트를 사용하여 이 문제점을 해결합니다. 

 

 

 

[ 자바스크립트 코드 & 스타일 추가]

 

 돋보기 아이콘도 input-box의 자식 요소이기 때문에 돋보기 아이콘이 눌리는 것은 input-box가 눌리는 것과 마찬가지입니다. 

 

 input-box가 눌리면 input의 상태를 포커스로 해주는 focusInput() 함수를 작성합니다. 

 

 

 만약 input 창이 포커스 되었다면, input-box의 클래스에 focused를 추가하고 input 창의 placehorder 속성을 추가합니다. 

 

 만약 input 창의 포커스가 해제, 즉 blur 처리 되었다면 input-box의 클래스에서 focused를 제거하고 placehorder에 아무 문장도 나타나지 않도록 합니다. 

 

 

const inputBox = document.querySelector('.input-box');
const input = document.querySelector('.input-box input');

/* 돋보기 아이콘 눌러도 input 창 포커스 되도록*/
function focusInput() {
  input.focus();
}

/* input 창 포커스 되면, 클래스와 속성 추가하기 */
function ifFocused() {
  inputBox.classList.add('focused');
  input.setAttribute('placeholder', '검색하기');
}

/* input 창 포커스 해제되면, 클래스와 속성 삭제하기 */
function ifBlured() {
  inputBox.classList.remove('focused');
  input.setAttribute('placeholder', '');
}

inputBox.addEventListener('click', focusInput);
input.addEventListener('focus', ifFocused);
input.addEventListener('blur', ifBlured);

 

 이제 input 창의 가로가 커지면, 돋보기 아이콘의 위치도 변경되는 스타일도 추가하겠습니다. 

 

.input-box.focused .material-icons {
  left: calc(200px - 24px - 5px);
}

 

 

반응형