[Nuxt3] input 검증 시 스크롤 움직임 및 포커스 거는 방법

쿼카쿼카·2023년 12월 16일
0

Vue / Nuxt

목록 보기
34/35

코드

export function moveToValidation(selector: string) {
  if (process.client) {
    const target = document.querySelector(selector);

    if (target) {
      target.scrollIntoView({ behavior: "smooth", block: "center" });
      target.focus();
    }
  }
}

process.client

  • util 함수들은 대부분 ts 파일로 묶여있기 때문에 process.client로 한 번 걸러줘야 document가 가능하다
  • document.querySelector를 이용해 원하는 요소를 가져온다.

scrollIntoView

  • target이 있다고? 그럼 scrollIntoView로 들어가라
  • scrollIntoView에는 behavior (동작 방식), block (수직 정렬), inline (수평 정렬)이 있다.
  • behavior

    • auto(default): 스크롤 움직임을 못생긴 기본 값으로 설정
    • smooth: 스크롤 움직임 슬릭백처럼 부드러운 움직임
    • instant: 스크롤 눈 깜짝할 사이에 한 방에 움직임
  • block inline

    • center: 요소의 위치를 가운데로
    • start, end: 처음과 끝
    • nearest(default): 가까운 곳

element.focus()

  • input, a태그 등 포커스가 가능한 요소에 포커스를 줌
  • 옵션에는 focusVisible, preventScroll이 있다.
  • focusVisible

    • 포커스 되는 게 보이는지 마는지? boolean으로 표현
    • 기본값은 true
  • preventScroll

    • 포커스 될 때 스크롤 이동 할지 말지 boolean으로 결정
    • 아니 이게 가능한 거였으면 굳이 scrollIntoView 쓸 필요가 있었냐??
profile
쿼카에요

0개의 댓글