SeouliteLab

jQuery의 :focus 선택자 활용하기 본문

프로그래밍

jQuery의 :focus 선택자 활용하기

Seoulite Lab 2024. 4. 12. 08:03

jQuery의 :focus 선택자는 현재 포커스가 있는 요소를 선택하는 데 사용됩니다. 사용자가 입력 필드나 버튼 등에 포커스를 주었을 때 해당 요소를 선택하여 스타일을 변경하거나 이벤트를 처리할 수 있습니다.

예제 1: 포커스된 입력 필드 스타일 변경하기

<!DOCTYPE html>
<html>
<head>
  <title>포커스된 입력 필드 스타일 변경</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("input:focus").css("border-color", "blue");
    });
  </script>
</head>
<body>
  <input type="text" placeholder="이름">
  <input type="text" placeholder="이메일">
</body>
</html>

설명: 위 예제는 입력 필드 중 포커스가 된 요소의 테두리 색상을 파란색으로 변경합니다.

예제 2: 포커스된 버튼 클릭 이벤트 처리하기

<!DOCTYPE html>
<html>
<head>
  <title>포커스된 버튼 클릭 이벤트 처리</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button:focus").click(function(){
        alert("버튼이 클릭되었습니다.");
      });
    });
  </script>
</head>
<body>
  <button>클릭하세요</button>
</body>
</html>

설명: 이 예제는 포커스가 된 버튼을 클릭하면 알림창을 띄웁니다.

예제 3: 포커스된 요소에 클래스 추가하기

<!DOCTYPE html>
<html>
<head>
  <title>포커스된 요소에 클래스 추가</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("*:focus").addClass("focused");
    });
  </script>
  <style>
    .focused {
      outline: 2px solid green;
    }
  </style>
</head>
<body>
  <input type="text" placeholder="이름">
  <button>클릭하세요</button>
</body>
</html>

설명: 이 예제는 포커스된 요소에 focused 클래스를 추가하여 초록색 테두리를 표시합니다.